Home / All Articles / How to Get Query Strings and Parameters in node js

How to Get Query Strings and Parameters in node js

Introduction

We’ll be going over how to extract information from a URL in node.js. Specifically, how do we extract information from a query string and URL path parameters?

In this article, I assume you have some experience with Node.js and creating Express.js servers (or at least simple ones) then you will be easily understand.

Extracting Query Parameters

Before we start, it’d be helpful to first understand what exactly a query string/parameter is, and then we’ll talk about how we can work with them.

So, what is a query parameter?

In simple terms, a query string is the part of a URL (Uniform Resource Locater) after the question mark (?). It is meant to send small amounts of information to the server via the url. This information is usually used as parameters to query a database, or maybe to filter results. It’s really up to you what they’re used for.

Here is an example of a URL with query strings attached:

http://stackabuse.com/?page=2&limit=3  

The query parameters are the actual key-value pairs like page and limit with values of 2 and 3, respectively.

Now, let’s move on to the first main purpose of this article – how to extract these from our Express request object.

This is a pretty common use-case in Express, and any HTTP server, so hopefully the examples and explanation I show here are clear.

Now, taking the same example from above:

http://stackabuse.com/?page=2&limit=3  

We’d like to extract both the page and limit parameters so we know which articles to return to the page that the user requested. While query parameters are typically used in GET requests, it’s still possible to see them in POST and DELETE requests, among others.

Your query parameters can be retrieved from the query object on the request object sent to your route. It is in the form of an object in which you can directly access the query parameters you care about. In this case Express handles all of the URL parsing for you and exposes the retrieved parameters as this object.

Let’s take a look at an example of us getting query parameters in a route:

const express = require('express');  
const bodyParser = require('body-parser');  
const url = require('url');  
const querystring = require('querystring');  
const Article = require('./models').Article;

let app = express();  
app.use(bodyParser.urlencoded({ extended: false }));  
app.use(bodyParser.json());

// Function to handle the root path
app.get('/', async function(req, res) {

    // Access the provided 'page' and 'limt' query parameters
    let page = req.query.page;
    let limit = req.query.limit;

    let articles = await Article.findAll().paginate({page: page, limit: limit}).exec();

    // Return the articles to the rendering engine
    res.render('index', {
        articles: articles
    });
});

let server = app.listen(8080, function() {  
    console.log('Server is listening on port 8080')
});

In the example above, we assume the page and limit parameters always exist. 
If neither of these parameters are given in the URL, we'd receive undefined for both page 
and limit instead.

Extract Query Parameters Without Express

As a quick bonus, I wanted to show you how to do the actual parsing on your own in case you need to extract information from a URL that isn’t using Express, or any other web framework. It’s fairly common to create a dead-simple server using the http module, so this is good to know.

Lucky for you, Node.js already provides some great core libraries that has this functionality built in, so it is just a matter of require-ing the module and calling a few lines of code.

Here is an example using the querystring and url packages.

const url = require('url');  
const querystring = require('querystring');

let rawUrl = 'http://stackabuse.com/?page=2&limit=3';

let parsedUrl = url.parse(rawUrl);  
let parsedQs = querystring.parse(parsedUrl.query);

// parsedQs = { page: '2', limit: '3' }

You can see in this code that we require two parsing steps to get the results we want.

Let’s break this down a bit further and show what exactly is going on at each step. After calling url.parse(rawUrl) on our URL, this is what is returned to us:

{
    protocol: 'http:',
    slashes: true,
    auth: null,
    host: 'stackabuse.com',
    port: null,
    hostname: 'stackabuse.com',
    hash: null,
    search: '?page=2&limit=3',
    query: 'page=2&limit=3',
    pathname: '/',
    path: '/?page=2&limit=3',
    href: 'http://stackabuse.com/?page=2&limit=3'
}

Okay, we’re a bit closer getting the data we need. But it needs to be broken down one more time. We can do this using the querystring package to parse the actual query string. For example:

let parsedQs = querystring.parse(parsedUrl.query);  

And finally, our parsedQs object contains the following:

{
    page: '2',
    limit: '3'
}

Extracting Route Parameters

In any web application another common way to structure your URLs is to place information within the actual URL path, which are simply called route parameters in Express. We can use these to structure web pages by information/data, which are especially useful in REST APIs.

Extracting these route parameters is similar to the query parameters. All we do is take the req object and retrieve our params from the params object. Pretty simple, right?

Let’s take a look at an example of doing this in our Express route:

// Route to return all articles with a given tag
app.get('/tag/:id', async function (req, res) {

    // Retrieve the tag from our URL path
    var id = req.params.id;

    let articles = await Article.findAll({tag: id}).exec();

    res.render('tag', {
        articles: articles
    });
});

First thing to notice is that we tell Express that our route is /tag/:id, where :id is a placeholder for anything. It could be a string or a number. So whatever is passed in that part of the path is set as the id parameter.

If we were to navigate to the URL http://stackabuse.com/tag/node then id would be node, and we’d get a bunch of articles that have the node tag on them. And req.params in this case would be {id: 'node'}, just like the query object.

As you can see, we again just take our parameter directly from an object contained within the request object.

About Sushil Kumar

Check Also

What is higher order function in JavaScript?

A higher-order function is a function that either takes another function as an argument or …

Leave a Reply

Your email address will not be published. Required fields are marked *