How to get the unparsed query string from a http request in Express

You can use req.originalUrl in express 3.x+. (Older versions can use req.url from node's http module.) This should produce the raw string, excluding the ?:

var query_index = req.originalUrl.indexOf('?');
var query_string = (query_index>=0)?req.originalUrl.slice(query_index+1):'';
// 'tt=gg&hh=jj' or ''

Note that if you have a # to denote the end of the query, it will not be recognized.

If you want to pass the string along to a new URL, you should include the ?:

var query_index = req.originalUrl.indexOf('?');
var query_string = (query_index>=0)?req.originalUrl.slice(query_index):'';
// '&tt=gg&hh=jj' or ''
res.redirect('/new-route'+query_string);
// redirects to '/newroute?tt=gg&hh=jj'

var queryString = Object.keys(request.query).map(key => key + '=' + request.query[key]).join('&');

or

var queryString = require('querystring').stringify(request.query);

You can use node's URL module as per this example:

require('url').parse(request.url).query

e.g.

node> require('url').parse('?tt=gg').query
'tt=gg'

Or just go straight to the url and substr after the ?

var i = request.url.indexOf('?');
var query = request.url.substr(i+1);

(which is what require('url').parse() does under the hood)


Express uses parseurl which stores _parsedUrl in the request object. Original string query can be accessed via request._parsedUrl.query.