Photo by Oskar Yildiz on Unsplash
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);
Extract 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.
Top comments (0)