【问题标题】:Express next() is triggering next route which is parameterised after next() from current route is calledExpress next() 正在触发下一个路由,该路由在调用当前路由的 next() 之后参数化
【发布时间】:2020-10-05 15:23:25
【问题描述】:

我有这条路线,/test,我调用了它,但不知何故,当在/test 路线最后调用 next() 时,它也触发了 /:async 路线?

router.post('/test/:value?'async (req, res: express.Response, next: express.NextFunction) => {|
   try{
     //code
   }catch(err){
     //log error
   }finally{
     next();
   }
})

router.post('/:id?'async (req, res: express.Response, next: express.NextFunction) => {
   try{
     //code
   }catch(err){
     //log error
   }finally{
     next();
   }
})

我在 server.ts 文件中有这个 finalResponseHandler 中间件,它应该在 next() 上调用。

app.use(finalResponseHandler);

如果我删除 /:id? 路由 finalResponseHandler 中间件被完美调用。
为什么调用这个 /:id 路由而不是 finalResponseHandler 中间件?
如何更正此问题以在调用“/test”路由时不调用/:id 路由。

感谢任何帮助。

【问题讨论】:

    标签: javascript node.js express routes express-router


    【解决方案1】:

    我猜这是因为 express 将其视为具有 /test/:value? 路径的中间件函数。和第二条路线一样,我建议你从/test/.... 中删除next()

    【讨论】:

    • 如果我删除next(),我将如何调用中间件finalResponseHandler
    • nex() 在应用程序的请求-响应周期中调用下一个中间件函数,因此您要么离开 next() 但必须在 /test 下添加中间件,或者如果您希望在 @ 之前调用中间件987654326@你可以像这样在路由中添加中间件router.post('/:id?', finalResponseHandler,async (req, res: express.Response, next: express.NextFunction)
    • 要求 finalResponseHandler 应该在处理路由之后调用,而不是之前。
    • 如果您希望中间件与路由无关,请将其放在您的主 index/app.js 中,它将始终在任何请求响应周期中调用
    • 是的,它在 app,js, app.use(finalResponseHandler);
    猜你喜欢
    • 2021-11-18
    • 1970-01-01
    • 2021-03-02
    • 2019-02-07
    • 2017-01-25
    • 2022-11-26
    • 2021-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多