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


Question

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?

1
1071
5/4/2015 12:01:05 PM

Accepted Answer

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] (https://nodejs.org/api/url.html#url_url_parse_urlstring_parsequerystring_slashesdenotehost) it manually:

var url = require('url');
var url_parts = url.parse(request.url, true);
var query = url_parts.query;
1023
1/26/2019 6:10:37 PM

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);

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon