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

; Date: Sun Jun 09 2013

Tags: Node.JS

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 '?').

For example, with the Express route declaration

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

In the req object, req.params.id 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: /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 req.query object with fields named for the parameter name.  There are plenty of other ways of using the req.query object, and the value appears anywhere Express provides the 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);
  } ...
}).listen(8124);

In other words, you have to use url.parse yourself.  When used as it is here, we get the full URL object which has more fields than the req.query object provided by Express.

About the Author(s)

(davidherron.com) David Herron : David Herron is a writer and software engineer focusing on the wise use of technology. He is especially interested in clean energy technologies like solar power, wind power, and electric cars. David worked for nearly 30 years in Silicon Valley on software ranging from electronic mail systems, to video streaming, to the Java programming language, and has published several books on Node.js programming and electric vehicles.

Books by David Herron

(Sponsored)