For the string, "http://localhost:9090/calculator?oper=add&n1=10&n2=20",
console.log(url.parse(req.url).query);
// gives `oper=add&n1=10&n2=20`
whereas
console.log(querystring.parse(req.url));
// gives { '/calculator?oper': 'add', n1: '10', n2: '20' }`
However, I'm not able to split it as these are objects, and not Strings. How do I convert them to strings?
Just use object.toString()
to convert any variable into a string. Most scalar types and arrays will be converted. Other objects might need to have the method implemented, otherwise they will just return the text [Object]
or something.
The second case it looks like console.log()
used JSON.stringify(object)
, probably because the object doesn't have a method toString()
implemented.
As you can see in what you provided, querystring.parse(req.url)
mixed the url path with the key of the zero'th value. This means that querystring.parse
should not be called on a full url, but only on the query part of the url. You can do that by using querystring.parse
on the result of url.parse
:
var parsedUrl = url.parse(testUrl); //would be url.parse(req.url)
var parsedQuery = querystring.parse(parsedUrl.query);
Now you can do parsedQuery.oper
, parsedQuery.n1
, parsedQuery.n2
If for some reason you want to iterate the parsedQuery (for example if you don't know the keys are oper
, n1
, n2
, ...), you can do it this way:
var parsedQueryKeys = Object.keys(parsedQuery);
parsedQueryKeys.forEach(function(key) {
console.log( key, parsedQuery[key] );
});
(There are multiple other solutions to iterate an object)
Finally, some libraries automate the parsing for you, so you can directly ask for the query values.
For example, with express's req.param
:
console.log( req.param('oper'), req.param('n1'), req.param('n2') );