Writing

Fetching Query and Route Parameters in ExpressJS

Slug
fetching-query-and-route-parameters-in-expressjs
Excerpt
How to access Query and Route Parameters in an Express.js App
2nd Posted URL
Action Items
Channel
DEV.TO
Next Action Date
Oct 28, 2021
Posted URL
Published Date
Oct 8, 2021
Status
Published
Type
Keywords
express,routes,query
Project

Introduction

Express.js is a popular backend web application framework for Node.js. While setting up your routes you might encounter scenarios where you need to fetch the parameters specified in the URL path to retrieve a particular set of data. This article will take you through how to extract values from URL route and query parameters.
We recommend you have some basic experience with Javascript and NodeJS and have setup simple routes using Express.js before you go on with this guide.

Extract Query Parameters

A Query String is the part that comes after the Question mark ? in a URL. Let's take an example URL.
https://example.com/api/users?type=admin&status=active
The URL above fetches a list of users with a type of admin and status is active .To fetch these values in Express you can access them using req.query object in your route handler.
const express = require('express') const app = express() app.get('/users', (req, res) => { const type = req.query.type; const status = req.query.status; }) app.listen(8080);
 

Extracting Route Parameters

On some routes we might want to fetch parameters that are specified within the URL path. Extracting these parameters is similar to the Query parameters. Let's take an example URL.
https://example.com/api/users/1
This URL fetches a User resource with and id of 1. Using Express we can write a single route handler that can fetch any User with any provided id . Lets take a look at an example.
const express = require('express') const app = express() app.get('/users/:id', (req, res) => { const id = req.params.id; }) app.listen(8080);
In this example, you can notice that the route specified is /users/:id , where :id represents the provided user id in the URL. Whenever we navigate to the URL with a value passed in that part of the path gets populated as the id parameter. We can fetch the id within the route in the req.params object.
 

Conclusion

We can see that we can access both Query and Route parameters from a URL using Express.js. If you need to do some added validation of the parameters you can check out express-validator to get the right data into your web app. I hope this guide will assist in better grasping Express.js as you use it in your projects.

Last edited on Tue Jun 06 2023

Hey there 👋

Was anything I wrote confusing, outdated, or incorrect? Please let me know! Just write a few words below and I'll be sure to amend this post with your suggestions.