Search code examples
expressurl-routingrouteparams

How to differentiate between 2 routes one of which is "/:param" and other is "/param"


I am a novice in expressjs and don't know much about routing and such concepts in expressjs. While reading about it, I saw that one can set a route like

route1 = app.get("/:param",callback)

where param will become the route param variable and all such get requests like: "/foo" or "/bar" will correspond to that route.

My question is: can I have a route now that is

route2 = app.get("/param", callback)

or

app.get("/anyOtherRoute",callback) 

If so, how can I know that the request is for route1 and not for route2 (or vice versa)?


Solution

  • You don't, really. But you can define your routes in an order such that you have different behaviour for anyOtherRoute.

    For example:

    app.get('/anyOtherRoute', doFoo); app.get('/:param', doBar);

    If doFoo terminates the request without calling next() you'll get the separation I think you're looking for.

    doFoo would be called first since express goes through the routes in the order that they are defined and added to the app.