How to get GET (query string) variables in Express.js on Node.js?

1,594,639

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
Share:
1,594,639
XMen
Author by

XMen

Updated on July 08, 2022

Comments

  • XMen
    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
      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
      drorw about 5 years
      Use the query object in express request - here are examples using express request query
    • John Balvin Arias
      John Balvin Arias almost 5 years
      @Dev01 he is not active since 2014 lol
    • Maitray Suthar
      Maitray Suthar almost 5 years
      If anyone looking for Nodejs API boilerplate with Expressjs and MongoDB. Try this: github.com/maitraysuthar/rest-api-nodejs-mongodb
    • KeshavDulal
      KeshavDulal over 2 years
      If you are confused between the terms url query and url params, you are not alone. stackoverflow.com/questions/30967822/…
  • pronebird
    pronebird over 12 years
    to retrieve GET variables in express.js you can use req.query.
  • Cris-O
    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
    pronebird over 12 years
    I didn't know req.param checks for req.query, thanks for this note.
  • mikermcneil
    mikermcneil over 12 years
    req.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
    user3167101 about 11 years
    Worth mentioning that you should use req.query.id, no need to use bracket notation.
  • pronebird
    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
    mikermcneil about 11 years
    Hey Andy- sorry, I misread your comment and thought you said "req.params" Not enough sleep, I guess!
  • befzz
    befzz almost 11 years
    attention here: .parse(url,true) url.parse(urlStr, [parseQueryString], [slashesDenoteHost])
  • BaltoStar
    BaltoStar almost 11 years
    What additional/better functionality does hapi provide ( if any ) ?
  • Cheeso
    Cheeso over 10 years
    This is accepted but it's not the preferred answer. See below! use req.query
  • danwellman
    danwellman over 10 years
    you don't need to require sys in this example
  • MindJuice
    MindJuice almost 10 years
    mikemcneil's answer below is a better choice. Use req.query or req.param (which is different than req.params...see below.
  • ossek
    ossek over 9 years
    won'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
    Joseph Juhnke over 9 years
    req.param('STRING') is the correct answer. See here: stackoverflow.com/questions/17007997/… (scroll down to answer below the accepted answer)
  • mikermcneil
    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
    whitfin over 9 years
    @ossek I believe the act of causing parse on req.url converts to an object.
  • Felipe
    Felipe over 9 years
    To install express do it: yes | sudo npm install -g express --- I tried to edit but Alexis King have been reverted.
  • Bharat
    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
    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 (use request.query)
  • Richard Torcato
    Richard Torcato almost 8 years
    in 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
    Alexander Craggs almost 8 years
    I 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
    Pavel P over 7 years
    totally agree, this answer is far from optimal. Why nobody corrected it then for such a long time
  • swang
    swang over 7 years
    req.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
    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 use req.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 of req.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
    nilakantha singh deo over 7 years
    res.send('Response send to client::'+req.query.id); would be a good choice.
  • xurei
    xurei almost 7 years
    Seems outdated. @yash-bele answer seems better, as you don't need any extra module.
  • Nico Haase
    Nico Haase almost 6 years
    Can you explain further how this answers the question?
  • Nico Haase
    Nico Haase almost 6 years
    And how does this parse an existing parameter list?
  • Mehedi Abdullah
    Mehedi Abdullah almost 6 years
    you may use body-parser module from node.js
  • user752746
    user752746 over 5 years
    I'm using express with node so this worked perfectly for me. Thank you!
  • Felipe Toledo
    Felipe Toledo about 5 years
    req.query worked for me! And It is the apropiate for string parameters
  • tiwarinitin94
    tiwarinitin94 almost 5 years
    in my case url.parse(req.url, true).query; worked
  • Lead Developer
    Lead Developer over 4 years
    Using object destructuring with default values! +1
  • Boaz
    Boaz almost 3 years
    When 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 the curl 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
    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
    KeshavDulal over 2 years
    for url-path-params (/user/:id), use req.params.id as above answer is for url-query-params (/user?id=123)
  • Quentin
    Quentin over 2 years
    '/' won't match /api/endpoint/:id and this is otherwise identical, but less informative, than the accepted answer.
  • Sahil Rajpal
    Sahil Rajpal over 2 years
    @Quentin thanks for pointing the mistake. I corrected that.
  • andylib93
    andylib93 about 2 years
    Exactly what I needed, perfect answer