Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express routes parameters

Tags:

I am trying to create two routes in my express app. One route, without a parameter will give me a list of choices, the other one with a parameter will give me the choice related to the id.

router.get('/api/choice', choice_controller.get_choices); router.get('/api/choice/:id', choice_controller.get_choice); 

When I go to .../api/choice/?id=1 the api returns the list of choices, and therefore follows the route without the param (/api/choice). How do I make sure that the router does not omit the parameter?

Thanks in advance.

UPDATE It seems that it does not fire the /api/choice/:id route. If I remove the one without the param, it gives a 404 so. Could someone explain to me why /api/choice/?id=1 is not getting picked up by /api/choice/:id?

like image 410
Bram Avatar asked Jan 10 '16 10:01

Bram


1 Answers

Basically, your declared routes are documented in the Express documentation.

The second route is resolved by a URL like /api/choice/hello where 'hello' is mapped into the req object object as:

router.get('/api/choice/:id', function (req, res) {   console.log("choice id is " + req.params.id); }); 

What you are actually trying is mapping query parameters.

A URL like /api/choice/?id=1 is resolved by the first router you provided. Query parameters are easy to get mapped against the request as:

router.get('/api/choice', function (req, res) {   console.log('id: ' + req.query.id);   //get the whole query as!   const queryStuff = JSON.stringify(req.query);   console.log(queryStuff) }); 
like image 160
vorillaz Avatar answered Nov 07 '22 17:11

vorillaz