2017-03-27 5 views
2

私はノードを新規に使用しています。私は "res.send"と "return res.send"の両方を使ってapp.getとapp.postの例を見てきました。これらは同じですか?app.get - res.sendと返信res.sendの間に違いがありますか?

var express = require('express'); 
var app = express(); 

app.get('/', function(req, res) { 
    res.type('text/plain'); 
    res.send('i am a beautiful butterfly'); 
}); 

または

var express = require('express'); 
var app = express(); 

app.get('/', function(req, res) { 
    res.type('text/plain'); 
    return res.send('i am a beautiful butterfly'); 
}); 

答えて

2

ので、その実行を終了するあなたの機能からreturnキーワード戻ります。これは、実行されないコードの後に​​続く行を意味します。

場合によっては、res.sendを使用してから、他の処理を行うことができます。

app.get('/', function(req, res) { 
    res.send('i am a beautiful butterfly'); 
    console.log("this gets executed"); 
}); 

app.get('/', function(req, res) { 
    return res.send('i am a beautiful butterfly'); 
    console.log("this does NOT get executed"); 
}); 
1
app.get('/', function(req, res) { 
    res.type('text/plain'); 
    if (someTruthyConditinal) { 
     return res.send(':)'); 
    } 
    // The execution will never get here 
    console.log('Some error might be happening :('); 
}); 

app.get('/', function(req, res) { 
    res.type('text/plain'); 
    if (someTruthyConditinal) { 
     res.send(':)'); 
    } 
    // The execution will get here 
    console.log('Some error might be happening :('); 
}); 
関連する問題