我开始使用 NodeJS/Express,遇到以下问题(我可能还没有掌握异步编程的所有技巧)
我制作了一个中间件,负责检查是否传递了 oauth_token 参数(实际上在我的 Node 服务器上实现了 oAuth 层)
我正在这样做:
function myMiddle(req,res,next) {
var oAuthToken = req.query["oauth_token"];
if (oAuthToken == undefined) {
res.send(406);
res.end();
next(new Error('No token provided'));
}
/* Basically doing some DB stuff with MongoDB, connecting and using oAuthToken provided to query, etc.. */
问题是,当他没有收到查询字符串中的 oauth_token 参数时,我预计代码会“死亡”。它实际上引发了一个错误,并向我的 HTTP 客户端返回了 406 错误,但是代码继续处理,并引发了由我之后的处理代码引起的可变 header 错误,并且我的脚本终止了。
我缺少什么吗?提前致谢。
最佳答案
如果您的oAuthToken
未定义 Node.js 会做出响应。之后你就开火 next(...)
它尝试对同一请求做出另一个响应。这失败了,你会看到你所看到的。请注意,在 Node.js 中使用 res.send();
和res.end();
不会停止你的功能。因此,您需要执行以下操作:
function myMiddle(req,res,next) {
var oAuthToken = req.query["oauth_token"];
if (oAuthToken == undefined) {
next(new Error('No token provided')); // handle everything here
// res.send(406);
// res.end();
// unnecessary, throws errors because you try to respond twice
}
// do something if this is fine
}
或者以其他方式进行 - 使用res.send(406); res.end();
没有next(...)
.
关于node.js - Express/Node.JS 中间件引发错误,继续处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9065269/