我应该在哪里放置中间件 nodejs
where should i place the middleware nodejs
**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
中间件发送响应并设置headers,这样调用errorHandler
或productRoutes
会导致常见错误Cannot set headers after they are sent
.如果你在路由之前定义中间件——它们首先被调用(我个人将它们命名为 'configurable middlewares' 或 'middlewares that configure my express app')。
但是,如果您在路由之后定义它们,它们将由 'route' 提供的 next()
函数调用。 next()
在路由之后调用下一个中间件 'in a queue'。
**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
中间件发送响应并设置headers,这样调用errorHandler
或productRoutes
会导致常见错误Cannot set headers after they are sent
.如果你在路由之前定义中间件——它们首先被调用(我个人将它们命名为 'configurable middlewares' 或 'middlewares that configure my express app')。
但是,如果您在路由之后定义它们,它们将由 'route' 提供的 next()
函数调用。 next()
在路由之后调用下一个中间件 'in a queue'。