Query strings are the ones that we usually pass as a key value pair in the url after a “?” symbol. Services may expect the user to supply information in the form of multiple query string parameters. In this article, we will see how to retrieve query string parameters in express.

Get Query String – Latest Versions Of Express

In the latest versions of express, query string is retrieved using the request (req) object. req.query will return a JavaScript object that has all the query string parameters and its values. Consider the below GET express service example that prints the query strings into console.

var express = require("express");
var app = express();
app.get('/example',function(req,res){
	//print all query strings.
 	console.log(req.query);
 	//print the value of a query string 'firstname'
 	console.log(req.query.firstname); 	
	res.send("Query String printed to console");
});
app.listen(8080);

After running the above code, make a call to the GET url with query strings.
eg: http://localhost:8080/example?fisrtname=MyName&age=22
Output:

{firstname: 'MyName', age: '22' } 
MyName

Example – Previous Express Versions

In the previous express versions, one should be able to retrieve the query string using req.param() function. Name of the query string should be supplied as an argument to get the value. Take a look at the below example where it retrieves the query string “firstname” and print to console.

app.get('/example',function(req,res){
 	console.log(req.param('firstname'));
	res.send("Query String printed to console");
});
Express Get Query String Parameters