Last updated on Dec 20, 2020 by Suraj Sharma
In this tutorial, you will learn how you can retrieve the query string params of a URL route in Express.js
Example of Query params in the URL
// URL
http://localhost:5000/api/content/?search=javascript&page=1&perPage=100
// Query string params
?search=javascript&page=1&perpage=100
The Request
object in Express contains a property called ‘query’, which contains the query params in key-value pairs
So the above query params example can be represented in key-value pairs as
const queryParams = {
search: 'javascript',
page: '1'
perPage: '100'
};
Therefore, we can use the Request.query
property object to retrieve the required query params from the URL route.
Source Code
const express = require('express')
const cors = require('cors');
const app = express();
const port = 5000;
app.use(cors());
app.get('/api/content', async (req, res) => {
const search = req.query.search;
const page = req.query.page;
const perPage = req.query.perPage;
res.send('success');
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
});
Related Solutions
Rate this post
Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.