Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send integers in query parameters in nodejs Express service

I have a nodejs express web server running on my box. I want to send a get request along with query parameters. Is there any way to find type of each query parameter like int,bool,string. The query parameters key value is not know to me. I interpret as a json object of key value pairs at server side.

like image 553
kishore Avatar asked Dec 03 '13 16:12

kishore


People also ask

Can query parameters be numbers?

It can feature various object types with distinct lengths such as arrays, strings, and numbers. It critical to note that query parameters can play a pivotal role in attribution, however, it is vitally essential to ensure that the attribution strategy is in the cross-platform, and it is performing everything it can.

How do I get query params Express?

Your query parameters can be retrieved from the query object on the request object sent to your route. It is in the form of an object in which you can directly access the query parameters you care about. In this case Express handles all of the URL parsing for you and exposes the retrieved parameters as this object.

Can we send query parameters in PUT request?

Is it OK to use query parameters in a PUT request? Absolutely. Query parameters are just another piece of the resource identifier.


3 Answers

You can't, as HTTP has no notion of types: everything is a string, including querystring parameters.

What you'll need to do is to use the req.query object and manually transform the strings into integers using parseInt():

req.query.someProperty = parseInt(req.query.someProperty);
like image 128
Paul Mougel Avatar answered Oct 23 '22 05:10

Paul Mougel


You can also try

var someProperty = (+req.query.someProperty);

This worked for me!

like image 20
parvezp Avatar answered Oct 23 '22 05:10

parvezp


As mentioned by Paul Mougel, http query and path variables are strings. However, these can be intercepted and modified before being handled. I do it like this:

var convertMembershipTypeToInt = function (req, res, next) {
  req.params.membershipType = parseInt(req.params.membershipType);
  next();
};

before:

router.get('/api/:membershipType(\\d+)/', api.membershipType);

after:

router.get('/api/:membershipType(\\d+)/', convertMembershipTypeToInt, api.membershipType);

In this case, req.params.membershipType is converted from a string to an integer. Note the regex to ensure that only integers are passed to the converter.

like image 10
Rori Stumpf Avatar answered Oct 23 '22 06:10

Rori Stumpf