Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I need to create url for get which is going to accept array, how in node.js/express extract array from request?

I need to create url for get which is going to accept array, how in node.js/express extract array from request ? I need to pass array with names which parametes I need to back from Person

model.

/api/person # here I need to pass which fields I want to see but to be generic.
like image 821
PaolaJ. Avatar asked Feb 27 '14 21:02

PaolaJ.


People also ask

How do you take an Array in node JS?

Inserting Data After creating an Array object, we can insert data. Use [] with index if you want to assign the value. array[0] = 3; array[1] = 5; array[2] = 12; array[3] = 8; array[4] = 7; You can also use the push() function to insert data.

What is req query in Express?

query is a request object that is populated by request query strings that are found in a URL. These query strings are in key-value form. They start after the question mark in any URL. And if there are more than one, they are separated with the ampersand.


3 Answers

One option is using a JSON format.

http://server/url?array=["foo","bar"]

Server side

var arr = JSON.parse(req.query.array);

Or your own format

http://server/url?array=foo,bar

Server side

var arr = req.query.array.split(',');
like image 109
Kevin Reilly Avatar answered Oct 17 '22 20:10

Kevin Reilly


You can encode an array in percent encoding just "overwriting" a field, formally concatenating the values.

app.get('/test', function(req,res){
    console.log(req.query.array);
    res.send(200);
});




localhost:3000/test?array=a&array=b&array=c

This query will print ['a','b','c'].

like image 42
durum Avatar answered Oct 17 '22 22:10

durum


Express exposes the query parameter as an array when it is repeated more than once in the request URL:

app.get('/', function(req, res, next) {
   console.log(req.query.a)
   res.send(200)
}

GET /?a=x&a=y&a=z:
// query.a is ['x', 'y', 'z']

Same applies for req.body in other methods.

like image 50
Muhammad Fawwaz Orabi Avatar answered Oct 17 '22 21:10

Muhammad Fawwaz Orabi