res.send,如何退出后?
在调用res.send()
,是否需要调用一个返回值或以某种方式退出callback函数,以确保没有进一步的代码执行? 就像在PHP中调用一个头函数时一样,你需要在之后调用exit来阻止进一步的代码被执行。
app.post('/create', function(req, res) { if(req.headers['x-api-key'] === undefined) { res.send({msg: "Goodbye"}); } // other code that should only be processed if it has that header. });
只需使用return:
app.post('/create', function(req, res) { if(req.headers['x-api-key'] === undefined) return res.send({msg: "Goodbye"}); // other code that should only be processed if it has that header. });
根据节点手册:
response.end()方法必须在每个响应中调用。
总是使用next()。
app.post('/create', function(req, res, next) { if(req.headers['x-api-key'] === undefined) { req.send({msg: "Goodbye"}); return next(); } // other code that should only be processed if it has that header. });