scarpacci
scarpacci

Reputation: 9204

Can I iterate over the query string parameters using ExpressJS?

I know that if I pass a URL like the below:

http://localhost:3000/customer?companyid=300&customerid=200

That I can then in ExpressJS use the below to extract the data:

res.send(util.format('You are looking for company: %s  customer: %s', req.query.companyid, req.query.customerid));

But, I would like to iterate over the paramters and handle them without having to predefine them in my query. I can't seem to find anything in the Express API, etc that seems to work (probably looking right over it).

http://localhost:3000/customer?companyid=300&customerid=200&type=employee

Any comments / suggestions would be appreciated!

Thanks,

S

Upvotes: 6

Views: 13969

Answers (2)

ase
ase

Reputation: 13491

In JavaScript you can look over the properties of an object using a for loop:

for (var propName in req.query) {
    if (req.query.hasOwnProperty(propName)) {
        console.log(propName, req.query[propName]);
    }
}

The hasOwnProperty check is to make sure that the property is not from the objects prototype chain.

Upvotes: 26

numbers1311407
numbers1311407

Reputation: 34072

req.query is just an object, so you can iterate over it like you would any object, e.g.

for (var param in req.query) {
   console.log(param, req.query[param]);
}

Upvotes: 8

Related Questions