How to get GET (query string) variables in Express.js on Node.js?
Solution 1
In Express it's already done for you and you can simply use req.query for that:
var id = req.query.id; // $_GET["id"]
Otherwise, in NodeJS, you can access req.url and the builtin url
module to url.parse it manually:
var url = require('url');
var url_parts = url.parse(request.url, true);
var query = url_parts.query;
Solution 2
Since you've mentioned Express.js in your tags, here is an Express-specific answer: use req.query. E.g.
var express = require('express');
var app = express();
app.get('/', function(req, res){
res.send('id: ' + req.query.id);
});
app.listen(3000);
Solution 3
In Express, use req.query
.
req.params
only gets the route parameters, not the query string parameters. See the express or sails documentation:
(req.params) Checks route params, ex: /user/:id
(req.query) Checks query string params, ex: ?id=12 Checks urlencoded body params
(req.body), ex: id=12 To utilize urlencoded request bodies, req.body should be an object. This can be done by using the _express.bodyParser middleware.
That said, most of the time, you want to get the value of a parameter irrespective of its source. In that case, use req.param('foo')
. Note that this has been deprecated as of Express 4: http://expressjs.com/en/4x/api.html#req.param
The value of the parameter will be returned whether the variable was in the route parameters, query string, or the encoded request body.
Side note- if you're aiming to get the intersection of all three types of request parameters (similar to PHP's $_REQUEST
), you just need to merge the parameters together-- here's how I set it up in Sails. Keep in mind that the path/route parameters object (req.params
) has array properties, so order matters (although this may change in Express 4)
Solution 4
For Express.js you want to do req.params
:
app.get('/user/:id', function(req, res) {
res.send('user' + req.params.id);
});
Solution 5
I learned from the other answers and decided to use this code throughout my site:
var query = require('url').parse(req.url,true).query;
Then you can just call
var id = query.id;
var option = query.option;
where the URL for get should be
/path/filename?id=123&option=456
XMen
Updated on July 08, 2022Comments
-
XMen almost 2 years
Can we get the variables in the query string in Node.js just like we get them in
$_GET
in PHP?I know that in Node.js we can get the URL in the request. Is there a method to get the query string parameters?
-
Dev01 over 6 years@whitequark's answer (the one with the most votes) should be marked as the correct answer. Do you mind updating it for others with the same question as you that stumble upon your question?
-
drorw about 5 yearsUse the query object in express request - here are examples using express request query
-
John Balvin Arias almost 5 years@Dev01 he is not active since 2014 lol
-
Maitray Suthar almost 5 yearsIf anyone looking for Nodejs API boilerplate with Expressjs and MongoDB. Try this: github.com/maitraysuthar/rest-api-nodejs-mongodb
-
KeshavDulal over 2 yearsIf you are confused between the terms
url query
andurl params
, you are not alone. stackoverflow.com/questions/30967822/…
-
-
pronebird over 12 yearsto retrieve GET variables in express.js you can use req.query.
-
Cris-O over 12 years@Andy req.params is better because: req.param(name[, default]) will: Return the value of param name when present or default. Checks route params (req.params), ex: /user/:id Checks query string params (req.query), ex: ?id=12Checks urlencoded body params (req.body), ex: id=12 To utilize urlencoded request bodies, req.body should be an object. This can be done by using the _express.bodyParser middleware.
-
pronebird over 12 yearsI didn't know req.param checks for req.query, thanks for this note.
-
mikermcneil over 12 yearsreq.param('parameterName') will check for req.body, req.query, and req.params, but if you want all of the query parameters as an object, you should use req.query.
-
user3167101 about 11 yearsWorth mentioning that you should use
req.query.id
, no need to use bracket notation. -
pronebird about 11 years@mikermcneil you probably mixed up req.param() and req.params (object). According to expressjs docs req.param() looks for value in all three objects. expressjs.com/api.html#req.param
-
mikermcneil about 11 yearsHey Andy- sorry, I misread your comment and thought you said "req.params" Not enough sleep, I guess!
-
befzz almost 11 yearsattention here: .parse(url,true)
url.parse(urlStr, [parseQueryString], [slashesDenoteHost])
-
BaltoStar almost 11 yearsWhat additional/better functionality does hapi provide ( if any ) ?
-
Cheeso over 10 yearsThis is accepted but it's not the preferred answer. See below! use
req.query
-
danwellman over 10 yearsyou don't need to require sys in this example
-
MindJuice almost 10 yearsmikemcneil's answer below is a better choice. Use
req.query
orreq.param
(which is different thanreq.params
...see below. -
ossek over 9 yearswon't id and option be undefined since query is just a string? we'd have to parse out the two separate parameters with a regex or the like.
-
Joseph Juhnke over 9 yearsreq.param('STRING') is the correct answer. See here: stackoverflow.com/questions/17007997/… (scroll down to answer below the accepted answer)
-
mikermcneil over 9 years@deltab here's a link to
req.params
in the Sails docs: sailsjs.org/#/documentation/reference/req/req.params.html and the new express docs: expressjs.com/4x/api.html#req.params -
whitfin over 9 years@ossek I believe the act of causing
parse
onreq.url
converts to an object. -
Felipe over 9 yearsTo install express do it: yes | sudo npm install -g express --- I tried to edit but Alexis King have been reverted.
-
Bharat about 9 years@ossek, he's provided true as a second argument to url.parse, which makes the query property point to an object ( and that internally uses querystring module) you can find more about it in the docs [here] (nodejs.org/docs/latest/api/…)
-
lunohodov about 8 years-1. Code above is a deadweight — something a good developer will refactor on the spot. This is an answer to "How to get the query string of an URL?" — the URL in question just happens to be in an object named
request
and has nothing to do with Express. See @whitequark's answer below (userequest.query
) -
Richard Torcato almost 8 yearsin the question he was looking for a way to get all the query string parameters like an array. The correct answer is this: app.get('/', function(req, res){ console.log(req.query); });
-
Alexander Craggs almost 8 yearsI don't suppose there's a method to take a group vote on unaccepting this answer and accepting the answer below? I'm terrified how many people this will have misled considering the 400,000 views.
-
Pavel P over 7 yearstotally agree, this answer is far from optimal. Why nobody corrected it then for such a long time
-
swang over 7 yearsreq.param is deprecated in express 4.x, should use req.params, req.body or req.query instead: expressjs.com/en/4x/api.html#req.param
-
mikermcneil over 7 years@swang is right- I double-checked with Doug Wilson recently about this, and the
req.param()
helper function is likely to be completely removed in Express 5. This won't be imminent until some time later in 2017, so I'll wait to edit this answer until then. In the mean time: It's safe to usereq.param()
with Express <=3.x / Sails <=0.12, and with the latest available release of Express 4, albeit w/ a deprecation log message. (For Sails users: The implementation ofreq.param()
will move into core as of Sails v1.0, and it will continue to be fully supported in Sails in the future.) -
nilakantha singh deo over 7 yearsres.send('Response send to client::'+req.query.id); would be a good choice.
-
xurei almost 7 yearsSeems outdated. @yash-bele answer seems better, as you don't need any extra module.
-
Nico Haase almost 6 yearsCan you explain further how this answers the question?
-
Nico Haase almost 6 yearsAnd how does this parse an existing parameter list?
-
Mehedi Abdullah almost 6 yearsyou may use body-parser module from node.js
-
user752746 over 5 yearsI'm using express with node so this worked perfectly for me. Thank you!
-
Felipe Toledo about 5 yearsreq.query worked for me! And It is the apropiate for string parameters
-
tiwarinitin94 almost 5 yearsin my case
url.parse(req.url, true).query;
worked -
Lead Developer over 4 yearsUsing object destructuring with default values! +1
-
Boaz almost 3 yearsWhen using
curl
in the shell to query the server, make sure to quote the URL. Otherwise, any ampersand (&
) sign in the URL will be treated as an extra command to be executed after thecurl
command. This could be very frustrating, as only the first query string param will be received in the server and no error will be thrown :) -
ICW almost 3 years@alex there's no advantage to using dot syntax over bracket notation. Really doesn't matter at all if you use one or the other
-
KeshavDulal over 2 yearsfor url-path-params (/user/:id), use
req.params.id
as above answer is for url-query-params (/user?id=123) -
Quentin over 2 years
'/'
won't match/api/endpoint/:id
and this is otherwise identical, but less informative, than the accepted answer. -
Sahil Rajpal over 2 years@Quentin thanks for pointing the mistake. I corrected that.
-
andylib93 about 2 yearsExactly what I needed, perfect answer