Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using multiple parameters in URL in express

I am using Express with Node and I have a requirement in which the user can request the URL as: http://myhost/fruit/apple/red.

Such a request will return a JSON response.

The JSON data, before the above call looks like:

{     "fruit": {         "apple": "foo"     } }   

With the above request, the response JSON data should be:

{     "apple": "foo",     "color": "red" } 

I have configured express to route as follows:

app.get('/fruit/:fruitName/:fruitColor', function(request, response) {     /*return the response JSON data as above using request.params.fruitName and  request.params.fruitColor to fetch the fruit apple and update its color to red*/     });   

But this does not work. I am unsure of how to pass multiple parameters, that is, I am unsure if /fruit/:fruitName/:fruitColor is the correct way to do this. Is it?

like image 744
callmekatootie Avatar asked Feb 28 '13 06:02

callmekatootie


2 Answers

app.get('/fruit/:fruitName/:fruitColor', function(req, res) {     var data = {         "fruit": {             "apple": req.params.fruitName,             "color": req.params.fruitColor         }     };       send.json(data); }); 

If that doesn't work, try using console.log(req.params) to see what it is giving you.

like image 120
chovy Avatar answered Oct 13 '22 04:10

chovy


For what you want I would've used

    app.get('/fruit/:fruitName&:fruitColor', function(request, response) {        const name = request.params.fruitName         const color = request.params.fruitColor      }); 

or better yet

    app.get('/fruit/:fruit', function(request, response) {        const fruit = request.params.fruit        console.log(fruit)     }); 

where fruit is a object. So in the client app you just call

https://mydomain.dm/fruit/{"name":"My fruit name", "color":"The color of the fruit"} 

and as a response you should see:

    //  client side response     // { name: My fruit name, color:The color of the fruit} 
like image 41
Esteban Morales Avatar answered Oct 13 '22 06:10

Esteban Morales