Express / Node.JS中间件引起错误,继续处理

我开始在NodeJS / Express下,我正面临以下问题(我可能还没有获得asynchronous编程的所有技巧)

我做了一个中间件负责检查是否传递了一个oauth_token参数(实际上是在我的节点服务器上实现了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.. */ 

问题是,当他没有收到查询string中的oauth_token参数时,我希望代码“死”。 这实际上引起了我一个错误,并且向我的HTTP客户端返回了大量的错误,但是代码一直在处理后面,并且引发了由于我的处理代码导致的可变标头错误,并且我的脚本死亡了。

我失踪的东西? 感谢提前。

如果您的oAuthToken未定义,则Node.js作出响应。 之后,你会触发next(...) ,试图对同一请求作出另一个响应。 这失败了,你看到你所看到的。 注意在Node.js中使用res.send();res.end(); 不会停止你的function。 所以你需要做的是:

 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(); res.send(406); res.end(); 没有next(...)

你的中间件堆栈中是否有明确的error handling( app.use(express.errorHandler())

有关如何使用next()详细信息,另请参阅Express中间件部分 。

这可能会晚,但我也遇到了这个问题。 您实际上可以将错误传递给ErrorHandler,以便中间件不会继续到下一个中​​间件或路由器,而您可以发送所需的HTTP状态代码。

你的中间件

 function myMiddle(req, res, next) { // Do validate your OAuth token // you might want to do better validation of the token here // instead of just checking its existence // // var oAuthToken = req.query['oauth_token']; // // According to JSLint, you can just directly select the object as: // // req.query.oauth_token if (req.query.oauth_token === undefined) { // Just let the ErrorHandler does the rest // like redirecting or just send message to client var err = new Error('Unauthorized access.'); err.status(406); // Or 403, or any HTTP status code // Pass it to ErrorHandler next(err); } else { // Do something here, or just next(); } } 

你的ErrorHandler

 app.use(function(err, req, res, next){ if (err.status == 406) { // You can just do res.sendStatus() res.sendStatus(406); // Set HTTP status code as 406 and send message to client // Or chaining res.status() with res.send() res.status(406).res.send(); // or res.render(), or res.json() return; } // Others }); 

有关ErrorHandler的更多信息: http : //expressjs.com/ja/guide/error-handling.html