Skip to content

How to get query strings and path parameters in Express.js?

In this article we will learn how to extract values from query strings and path parameters from an Express.js request. In Express.js routes / services we needs to get values from query strings and route params and use them in the business logic. This tutorial explains the process of extracting these values after validations.

Extract Query Parameters

Let’s take an example URL.

The above API fetches dashboard for type user and format bar.

To fetch these values you can use req.query.type and req.query.format

let type = req.query.type;
let format = req.query.format;
console.log(type); //user
console.log(format); //bar

Extract Path Parameters

The same URL that we used in the previous example can also be framed to use path params.

Your route configuration would look something like this.

routes.get('/:type/:format', dashboardService.getHomePage(req, res);

Here type user and format bar are passed in the URL as path parameters.

To extract these values in the code, you can use req.params.type and req.params.format

let type = req.params.type;
let format = req.params.format;
console.log(type); //user
console.log(format); //bar
See also  How to Dockerize your node.js application?

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.