0

I have this route, /test which I called but somehow it is triggering /:async route as well when next() is called in /test route's finally?

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();
   }
})

I have this finalResponseHandler middleware in server.ts file which is supposed to be called on next().

app.use(finalResponseHandler);

If I remove /:id? route finalResponseHandler middleware is called perfectly.
Why is this /:id route is getting called instead of finalResponseHandler middleware?
How do I correct this to not call /:id route when calling '/test' route.

Any help is appreciated.

Helping hand
  • 2,800
  • 2
  • 19
  • 31

1 Answers1

0

I guess the reason for that it's because express see this as a middleware function with a /test/:value? path. and the same for the second route, i suggest you remove next() from /test/....

Sven.hig
  • 4,449
  • 2
  • 8
  • 18
  • If I remove `next()` how would I call middleware `finalResponseHandler`? – Helping hand Jun 16 '20 at 05:59
  • nex() calls the next middleware function in the application’s request-response cycle so you either leave next() but then you have to add the middleware underneath /test or if you want the middleware called before `/:id` you can add the middleware to the route like this `router.post('/:id?', finalResponseHandler,async (req, res: express.Response, next: express.NextFunction)` – Sven.hig Jun 16 '20 at 06:05
  • requirement is finalResponseHandler should be called after processing the route, not before. – Helping hand Jun 16 '20 at 06:08
  • if you want the middleware to be route agnostic, put it in your main index/app.js and it will be always called for any request response cycle – Sven.hig Jun 16 '20 at 06:09
  • Yes it is in app,js, `app.use(finalResponseHandler)`; – Helping hand Jun 16 '20 at 06:09
  • so you want it to be called after /test and after /:id ? is that correct? – Sven.hig Jun 16 '20 at 06:12
  • I want middleware to be called after /test/ but do not want to trigger /:id route in any way. – Helping hand Jun 16 '20 at 06:16
  • then you have to require and add the middleware underneath /test or add it to the route right after you send the response – Sven.hig Jun 16 '20 at 06:24