Search code examples
javascriptexpressbackendmiddleware

ExpressJS - How to jump to the next middleware which has initial url defined


Example code:

app.use('/list-product', (req, res, next) => {
  // Do stuff
  next();
})

app.use('/add-product', (req, res, next) => {
  console.log("I'm here")
})

Somehow it doesn't log "I'm here'", which means next() call doesn't work.

But if I change '/add-product' to '/' or I remove it at all, it works. Why is that?

How can I jump to the next middleware which has initial url on it as the example above?


Solution

  • It sounds like you don't quite understand that when you put a path in front of the middleware, the URL must a least be a partial match for that path for that middleware to be called at all.

    So, when you do a request for /list-product, that will match your /list-product middleware which will then call next(). That will continue on the middleware chain looking for other middleware handlers that match the /list-product path. When it gets to your next middleware for /add-product, that doesn't match /list-product so it is skipped (not called).

    If you change app.use('/add-product', ...) to app.use('/', ...) or to app.use(...) with no path, then those last two are matches for /list-product so they will get called. The / middleware is a partial match (for all URLs) and middleware with no path will be called for all URLs. app.use() runs for partial matches. The more specific request handlers like app.get() and app.post() require a more complete match.