How does Express routing with optional parameters work?

At the moment I am routing like this:

app.get('/post/:id?/:edit?/:add?') // ... func and something else

      

When I send url request '/post/'

, no parameters, it gets all messages.

B '/post/5'

, where 5 is the id of the message, it receives the message with id 5 in db.

A '/post/5/edit'

page opens with a form for editing the current message.

Things are good. But when I try to open 'post/add/

it did not work, because it req.params

shows the console that: id: 'add', edit: undefined, add: undefined

. How to fix it?

+3


source to share


1 answer


req.params is basically an array, so in your case the first parameter req.params [0] will always be req.params.id no matter what value you provide and your program will think that you are trying to get a message with id 'add'.



You might want to post / add a separate route, this will be easier.

0


source







All Articles