I have an express API with a bunch of routes.
routes.get('/', perms('read', 'document'), r(CRUD.getAll))
routes.get('/search', perms('read', 'document'), r(CRUD.search))
routes.get('/:id', perms('read', 'document'), r(CRUD.getById))
I made sure to have /search above /:id, however, when a new request comes in to /search, I see both endpoints getting a hit (I added a console.log inside of each function).
I tried flipping the two and in that case, only /:id gets a hit.
Any idea of why this may be happening?
CodePudding user response:
Think about Express routing as an array of handlers (middlewares), that have a matching rule (url). When a request comes in, the router starts checking each item from the array. If it matches the rule, then it's run (some don't have conditions, so they just run :)). The request chain does not end when a url is matched! You can execute multiple handlers/middlewares on the same request.
Therefore, it really depends on what happens inside your handler. You can tell it to go to the next item in the list, and if there's another match - the next handler will be executed (like /search and /:id, which will be search again).
Make sure you end your response. Beware if you call next and with what parameters. Post some samples of the handlers in order to debug it more :)

