user3871
user3871

Reputation: 12716

Express Router reading two different dynamic routes the same

How can I specify an optional parameter with Express Router? This resource says to use ? after the param.

Basically, I usually hit /posts endpoint just to get all posts. But sometimes I need to add in a type filter and get all Posts based on that type. The routing instead is reading my /posts/:id as the same dynamic route as /posts/:type and so when I need to make a getOne request from /posts/:id, it doesn't ever hit that because it hits /:type instead and does a regular Posts.get.

These are different routes, but Router is reading them as the same.

React frontend:

getPosts(type) {
    return http({
        method: 'GET',
        url: `${url}/${type}`,
        data: data
    });
}

NodeJS Express Router backend:

/* Posts CRUD */
router.route('/posts/:type?')
  .get(Posts.get)
  .post(Posts.post);

/* Post CRUD */
router.route('/posts/:id')
  .get(Posts.getOne)
  .put(Posts.put)
  .delete(Posts.delete);

To clarify: I need routes with :type param to do a .get(Posts.get) and routes with :id param to do a .get(Posts.getOne)

Upvotes: 0

Views: 930

Answers (1)

Aman Gupta
Aman Gupta

Reputation: 3797

In the doc, it says that if you put a parameter between : & ?, that parameter is optional i.e.

app.get('/route/:id/:op?',...)

means that I can have '/route/1' as well as '/route/1/delete' as endpoint.

For your situation, you have to use different route for one of them to remove ambiguity.

Better use router.route('/post/:id') for getting one item as posts is plural anyways :)

Upvotes: 2

Related Questions