Express路由 – 未经授权的error handling程序挂起错误路由

我正在使用从教程书中抓取的这段代码。 我实现了护照和应用程序的用户。使用检查UnauthorizedError是教程推荐的方法来检查检查未经授权的访问应用程序的受限制的部分。

每当我input一个错误的url,网站只是挂起,没有error handling,没有消息发送到浏览器。 我昨天花了很多时间检查我的路线,似乎没有明显的问题。

然后今天用一个小的预感,我注意到错误检查Unauthorized error ,瞧,error handling是一切都很好。 任何有关这里发生的事情的build议,以及如何正确实施这个错误检查?

注意:当有一个真正的未经授权的访问一个已知的url良好的路线,这个错误检查确实工作。 但是,即使login,它仍然没有收到错误的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; 

也许,你必须调用next()将错误转发给下一个error handling程序。

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