Reputation: 468
My team is developing an API nodejs with express and we are wondering if those routes are gonna be in conflict:
If someone got an information for this please.
Upvotes: 0
Views: 1098
Reputation: 191
The first route matches the request will win! It means that both could match the same request. Thus, you should put the most specific one first, i.e., "/aws/volumes/types". This way, it will run the handler for the "types" route if you request "/aws/volumes/types", otherwise, it will run the handler for the ":id" route.
Also, you can use regular expression if you want to be more precise with what you expect as an ":id". See more here: http://expressjs.com/en/guide/routing.html in the "route paths" section.
Finally, you can also try next('route')
instruction in this case. Instead of just calling next()
which will call the next middleware of the same route, next('route')
will pass control to the next matching route handler. See the answer here: What is the difference between next() and next('route') in an expressjs app.VERB call?
Upvotes: 0
Reputation: 1370
Yes, These routes will conflict. If you provide the routes in the below order, it always hit the first route though you call '/aws/volumes/types'.
If you provide the routes as below, then they won't result in conflict.
Upvotes: 2
Reputation: 23042
They will conflict. For example,
If you define GET /aws/volumes/:id
first, then all of the below will point to it:
GET /aws/volumes/example
GET /aws/volumes/qwerty
GET /aws/volumes/types
You could alternatively do for the second route to get around the above:
GET /aws/volumes?q=types
Upvotes: 1