【问题标题】:Express routing - Unauthorized Error handler hanging up the error routes快速路由 - 挂起错误路由的未经授权的错误处理程序
【发布时间】:2016-07-10 11:05:45
【问题描述】:

我正在使用从教程书中获取的这段代码。我用护照实现了用户,app.use 检查UnauthorizedError 是教程推荐的检查对应用程序受限部分的未授权访问的方法。

每当我输入错误的网址时,网站就会挂起,没有错误处理,也没有消息发送到浏览器。我昨天花了很大一部分时间检查我的路线,似乎没有明显的问题。

然后,今天我凭着一个小小的预感将Unauthorized error 的错误检查注释掉了,瞧,错误处理又好了。关于这里发生的事情以及如何正确实施此错误检查的任何建议?

注意:当存在对已知 URL 良好路由的实际未经授权访问时,此错误检查确实有效。但是,即使已登录,它仍然不会捕获错误的 url。

app.use('/', routes);
app.use('/api', routesApi);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);  
});

// error handlers
// Catch unauthorised errors
app.use(function (err, req, res, next) {
  if (err.name === 'UnauthorizedError') {
    res.status(401);
    res.json({"message" : err.name + ": " + err.message});
  }
});

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});


module.exports = app;

【问题讨论】:

    标签: node.js express routing


    【解决方案1】:

    也许,您必须调用 next() 将错误转发到下一个错误处理程序。

    app.use(function (err, req, res, next) {
      if (err.name === 'UnauthorizedError') {
        res.status(401);
        res.json({"message" : err.name + ": " + err.message});
      } else
        next(err);
    });
    

    【讨论】:

    • 不是……就是这样!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 2018-10-07
    • 1970-01-01
    • 2020-01-25
    • 2017-02-03
    • 1970-01-01
    相关资源
    最近更新 更多