Parameters and Query Strings in Express.js

I’ve recently been dabbling on Node.js and it’s been a really awesome server platform. So naturally, I’ve needed to use Express.js for scripting. This also means that I’ve been dealing with parameters and query strings. They’re very important if you’re a server-side developer no matter which scripting language you use. They help accomplish many things like web service API’s. Although these are common and straightforward for server-side development, I’d like to share my understanding of them.

For this demonstration, I’m using Express 4.

In order to make things simpler, I used the middleware body-parser to parse URL-encoded body. It helps when sending JSON data to the client from the server or vice versa. The client in this example is POSTMAN.


npm install --save body-parser

Include body-parser at the top of code file.


var bodyParser = require('body-parser');

Configure body-parser to be linked with Express.


...
var app = express();

// Config body-parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

The whole code at this point looks something like this:


// Express
var express = require('express');
// body-parser
var bodyParser = require('body-parser');

var app = express();

// Set port
app.set('port', process.env.PORT || 8080);

// Config body-parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

/* Routes to handle Parameters and Query Strings 
   will be added here 
***************************************
*                                      *
*                                      *
*                                      *
****************************************/

app.listen(app.get('port'), function() {
 console.log('Server started on localhost:' + app.get('port') + '; Press Ctrl-C to terminate.');
});

What are query strings?

Query strings are the data that appear in a page URL. They are appended after the URL path and preceded by a question mark. Each of them take the form of name-value pair. Since they appear in the URL, they’re not confidential. So anyone can see them. These data are optional but are useful information when sending a request to the server. Query strings start with a question mark and each name-value pair are separated by an ampersand &. A URL with a query string looks like this:

http://localhost:8080/dog?breed='Whippet'

Using Express, the server will obtain a query string by taking the request object’s query property followed by the name of the a query string name-value pair. In the code snippet below, GET method is declared having dog as a path.


app.get('/dog', function(req, res) {
   res.json({ querystring_breed: req.query.breed });
});

IN POSTMAN, do a GET request and type


http://localhost:8080/dog?breed='Whippet'

POSTMAN will receive a response { "querystring_breed": "'Whippet'"} If there are no query strings, POSTMAN receives an empty object { }.

Using POSTMAN to get query string

To add another query string like, age, the URL looks like this:

http://localhost:8080/dog?breed='Whippet&age=10'

And, you obtain it by simply adding another property in the response json object.


app.get('/dog', function(req, res) {
   res.json({ querystring_breed: req.query.breed,
          age: req.query.age });
});

The output to the client is { "querystring_breed": "'Whippet'", "age": "10" }

Using POSTMAN to get two query strings in express.js and node.js

What are parameters?

Parameters don’t take the name-value form; they don’t need any key. Simply append the value to the URL right after the path. To prevent confusion with query strings,

  1. make sure that parameters aren’t preceded by a question mark
  2. that they are appended right after the URL path
  3. and they are succeeded by query strings.

In Express, parameters must be declared unlike query strings that are optional. The parameter in this example is name


app.get('/dog/:name', function(req, res) {
    res.json({ parameter_name: req.params.name });
});

Notice the URL below that after the domain name and path, there’s a forward slash followed by the word Devo. Devo is the parameter value. To test, do a GET in POSTMAN with this URL


http://localhost:8080/dog/Devo/

Using POSTMAN to get parameters in express.js and nodel.js

If you want more than one parameter simply make another endpoint or modify the current one like so:


app.get('/dog/:name/:id', function(req, res) {
   res.json({ parameter_name: req.params.name,
              id: req.params.id });
});

And, the URL to use in POSTMAN looks like this

http://localhost:8080/dog/Devo/123

Combine parameters and query strings

Parameters always come right after the domain, a port if there’s one, and a path. It should never be before query strings. Query strings are after the parameters.

So check out this URL. It starts with a domain (or hostname) followed by a colon and a port number. The port number is then followed by the path dog. Right after that path is the value Devo for parameter name. Then, it’s followed by a question mark and a query string.


http://localhost:8080/dog/Devo?breed='Whippet'

Send a response json object back to the client like this


app.get('/dog/:name/', function(req, res) {
   res.json({ dog_name: req.params.name,
             dog_breed: req.query.breed });
});

Get parameters and query strings in Express.js and Node.js

Although this article only shows GET endpoints, you can use parameters and query strings on other HTTP requests like POST PUT and DELETE as well. Simply replace .get with .post for POST endpoint like this


app.post('/dog/:name/:id', function(req, res) {
   res.json({ dog_name: req.params.name,
              dog_id: req.params.id,
              dog_breed: req.query.breed });
});