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

Express/Node.JS中间件引发错误,继续处理,node.js,asynchronous,express,Node.js,Asynchronous,Express,我从NodeJS/Express开始,我面临以下问题(我可能还没有掌握异步编程的所有技巧) 我制作了一个中间件,负责检查是否传递了oauth_令牌参数(实际上在我的节点服务器上实现了oauth层) 我正在这样做: function myMiddle(req,res,next) { var oAuthToken = req.query["oauth_token"]; if (oAuthToken == undefined) { res.send(406);

我从NodeJS/Express开始,我面临以下问题(我可能还没有掌握异步编程的所有技巧)

我制作了一个中间件,负责检查是否传递了oauth_令牌参数(实际上在我的节点服务器上实现了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_令牌参数时,我希望代码“死亡”。它实际上会给我带来一个错误,并将406错误返回给我的HTTP客户机,但代码一直在后面处理,并在之后引发由处理代码引起的可变头错误,我的脚本就死了


我错过了什么?提前感谢。

您的中间件堆栈中是否有快速错误处理(
app.use(express.errorHandler())


另请参阅,以获取有关如何在您的
oAuthToken
未定义的节点时使用
next()
的详细信息。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()

您的中间件

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的更多信息:

是的,我有错误处理程序。实际上,我通过返回next(“错误”)而不是调用next来“解决”(不确定它是否干净)。我想这是有意义的,因为它使函数退出。我也尝试了这一点,代码继续处理。正如我在下面的评论中所说,我通过返回next来修复它('error')而不是仅仅调用它。对你来说这似乎是逻辑吗?它不是。:D实际上是这样的,它只意味着你在调用
next()
后强制函数停止工作。也许你应该修改一点我的代码,并使用
if{…}else{…}
?重要的是没有任何东西(与响应有什么关系)在
next()
之后运行。我只能说,祝你好运!