【发布时间】:2021-05-31 12:25:24
【问题描述】:
**app.get('/', (req,res)=>{
res.send('Api is running...');
})
app.use('/api/products/', productRoutes);
app.use(notFound);
app.use(errorHandler);**
上面是我的代码的要点,其中 app.use(notFound) 和 app.use(errorHandler) 是中间件。 这种模式工作得很好。 但是,当我将命令的位置交换到下面时,应用程序就会中断。中间件要放在底部吗?请帮我解决我的困惑。
**app.get('/', (req,res)=>{
res.send('Api is running...');
})
app.use(notFound);
app.use(errorHandler);
app.use('/api/products/', productRoutes);**
【问题讨论】:
-
调用notFound中间件的时候,通常会有一个逻辑抛出错误,传递给next(),也就是errorHandler。因此它将继续执行 erorrHandler 中的任何内容(主要是向客户端返回一些错误)。因此,为避免这种情况,您需要将路由器文件放在错误处理程序之上。
标签: node.js express middleware