Growler Growler - 8 months ago 86
Node.js Question

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
endpoint just to get all posts. But sometimes I need to add in a
filter and get all Posts based on that type. The routing instead is reading my
as the same dynamic route as
and so when I need to make a
request from
, it doesn't ever hit that because it hits
instead and does a regular

These are different routes, but
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 */

/* Post CRUD */

To clarify: I need routes with
param to do a
and routes with
param to do a


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


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 :)