How to get URL params after '?' in Express.js or Node.js?

Date: Mon Jun 19 2017 Routing »»»» Express
Express makes it easy to route parameterized URL's to a handler function, and easily grab data out of the request URL.  This makes it easy to build a web application, that puts data into the URL, with clean URL's out of the box.  That's so much nicer than other application frameworks that require abominations like mod_rewrite to get clean URL's.  However nice the parameterized URL's are in Express, they do not handle other parts of the URL such as query parameters (the part of the URL after the '?').

Click here for more Node.js programming advice

For example, with the Express route declaration

app.get('/user/:id', user.load, ...)

In the <span style="font-family: " courier="" new",courier,monospace;"="">req object, <span style="font-family: " courier="" new",courier,monospace;"=""> will contain whatever string was passed in the URL.  This is quite convenient and automatically results in clean URL's.  There are times we'll naturally end up with query strings, like for FORM submissions.

Suppose we're using a query parameter to specify the language on an internationalized site.  Each URL could have a query parameter

<span style="font-family: " courier="" new",courier,monospace;"="">/path/to/resource?lang=ro-RO

In this case you would use an Express route middleware function like this:

var getLang = function(req, res, next) {
  if (req.query.lang) {
     // do something with language string
  } else {
    // set default language .. e.g. en-US

Which you would then use in a route like so

app.get('/path/to/resource', getLang, routes.whatEver);

Generally speaking, the query parameters appear in the <span style="font-family: " courier="" new",courier,monospace;"="">req.query object with fields named for the parameter name.  There are plenty of other ways of using the <span style="font-family: " courier="" new",courier,monospace;"="">req.query object, and the value appears anywhere Express provides the <span style="font-family: " courier="" new",courier,monospace;"="">req object.

It's straightforward, then, to access query parameters in Express, because Express does it for you.  How do you do this if you're not using Express?

The Node.js HTTP Server object doesn't do this for you automatically but it's possible to code a server that handles query parameters.

var http    = require('http');
var url     = require('url');
var server = http.createServer(function (req, res) {
  req.requrl = url.parse(req.url, true);
  if (req.requrl.pathname === '/path/to/resource') {
    handlerFunction(req, res);
  } ...

In other words, you have to use <span style="font-family: " courier="" new",courier,monospace;"="">url.parse yourself.  When used as it is here, we get the full URL object which has more fields than the <span style="font-family: " courier="" new",courier,monospace;"="">req.query object provided by Express.

Learn more about Node.js programming