快递:如何将请求传递给特定的处理程序?
在我的Express应用程序中all('/', ...)
根path上有一个all('/', ...)
。 在这里,我检查失败标志,并希望将请求传递给next
处理程序,或者如果发生错误,就像无法build立数据库连接,或者我想直接将请求传递给/error
路由,但是我不不想redirect。
可以将请求直接表示为/error
还是必须显式调用该路由的处理程序?
app = express() var errors = ... app.all('/', (req, res, next) => { if(errors) { // route to /error } else { next() } }) app.get('/error', (req, res, next) => { ... })
您可以分别为错误路由定义处理程序,然后直接调用它,而不是调用next,但是您真正想要的是定义error handling中间件 。 就像是:
app.all('/', (req, res, next) => { if(errors) { next(errors) } else { next() } }) app.use((err, req, res, next) => { ... })