【问题标题】:where should i place the middleware nodejs我应该在哪里放置中间件 nodejs
【发布时间】: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


【解决方案1】:

实际上,是的,我建议notFound 中间件发送响应并设置标头,以便调用errorHandlerproductRoutes 导致常见错误Cannot set headers after they are sent。如果你在路由之前定义中间件——它们会被首先调用(我个人将它们命名为“可配置的中间件”或“配置我的快速应用程序的中间件”)。

但是如果你在路由之后定义它们,它们将被“路由”提供的next() 函数调用。 next() 在路由之后调用“队列中”的下一个中间件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-17
    • 2019-04-18
    • 2012-07-10
    • 2015-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多