Node.js app.get-res.send和return res.send之间有什么区别吗
我不熟悉node和express。我已经看到app.get和app.post示例使用了“res.send”和“return res.send”。这些是一样的吗Node.js app.get-res.send和return res.send之间有什么区别吗,node.js,express,Node.js,Express,我不熟悉node和express。我已经看到app.get和app.post示例使用了“res.send”和“return 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'); }); 或 retur
var express = require('express');
var app = express();
app.get('/', function(req, res) {
res.type('text/plain');
res.send('i am a beautiful butterfly');
});
或
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");
});
我想指出它到底在我的代码中起了什么作用 我有一个对令牌进行身份验证的中间件。代码如下:
function authenticateToken(req, res, next) {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1] || null;
if(token === null) return res.sendStatus(401); // MARKED 1
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, user) => {
if(err) return res.sendStatus(403); // MARKED 2
req.user = user;
next();
});
}
在//标记的1
行上,如果我没有写入return,中间件将继续调用next()
,并发送状态为200
的响应,而这不是预期的行为
这同样适用于like//标记2
如果未在这些If
块中使用return
,请确保使用调用next()
的else
块
希望这有助于理解概念并从一开始就避免bug。是的!我用例子解释得很好。
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 :(');
});
function authenticateToken(req, res, next) {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1] || null;
if(token === null) return res.sendStatus(401); // MARKED 1
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, user) => {
if(err) return res.sendStatus(403); // MARKED 2
req.user = user;
next();
});
}