Express Request Query parameters
In Express.js, query parameters are key-value pairs that appear in the URL after the ?
symbol. They are commonly used to pass additional information to the server, such as search filters, pagination settings, or configuration options. These parameters are not part of the path of the URL but are appended to it. Express provides access to query parameters through the req.query
object.
Structure of Query Parameters
The structure of a URL with query parameters looks like this:
http://example.com/path?key1=value1&key2=value2
?
separates the path from the query string.key1=value1
is a query parameter, withkey1
as the key andvalue1
as its value.- Multiple parameters can be added, separated by an
&
, such askey2=value2
.
Example of Query Parameters in a URL
http://localhost:3000/search?term=books&category=fiction
In this URL:
- The path is
/search
. - The query parameters are
term=books
andcategory=fiction
.
Accessing Query Parameters in Express.js
To access query parameters, you can use req.query
, which returns an object containing all the key-value pairs from the query string.
Example
const express = require('express');
const app = express();
app.get('/search', (req, res) => {
const term = req.query.term; // Access the 'term' query parameter
const category = req.query.category; // Access the 'category' query parameter
res.send(`Search term: ${term}, Category: ${category}`);
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
For a request to http://localhost:3000/search?term=books&category=fiction
, the response will be:
Search term: books, Category: fiction
Handling Multiple Query Parameters
You can handle multiple query parameters at once by simply accessing each key from req.query
.
Example
app.get('/products', (req, res) => {
const { sortBy, limit } = req.query; // Destructure the query parameters
res.send(`Sort by: ${sortBy}, Limit: ${limit}`);
});
For a request to http://localhost:3000/products?sortBy=price&limit=10
, the response will be:
Sort by: price, Limit: 10
Default Values for Query Parameters
Sometimes, query parameters may not be provided by the client. You can set default values in your route handler to handle such cases.
Example with Default Values
app.get('/items', (req, res) => {
const page = req.query.page || 1; // Default to page 1 if 'page' is not provided
const limit = req.query.limit || 10; // Default to 10 items per page
res.send(`Page: ${page}, Limit: ${limit}`);
});
For a request to http://localhost:3000/items
, the response will be:
Page: 1, Limit: 10
Handling Arrays in Query Parameters
If multiple values are passed for the same query parameter key, Express will parse them as an array.
Example
app.get('/filter', (req, res) => {
const categories = req.query.categories; // Access the 'categories' parameter
res.send(`Selected categories: ${categories}`);
});
For a request to http://localhost:3000/filter?categories=books&categories=electronics
, the response will be:
Selected categories: books,electronics
In this case, categories
will be an array: ['books', 'electronics']
.
Handling Query Strings with URL-Encoding
Sometimes, special characters like spaces or symbols need to be included in query parameters. In such cases, query parameters are URL-encoded.
For example, for the query http://localhost:3000/search?term=best books
, the space between "best" and "books" should be URL-encoded as %20
, resulting in term=best%20books
.
Express automatically decodes URL-encoded query strings, so you don't need to manually decode them.
Example
app.get('/search', (req, res) => {
const term = req.query.term; // 'term' will be 'best books'
res.send(`Search term: ${term}`);
});
For a request to http://localhost:3000/search?term=best%20books
, the response will be:
Search term: best books
Parsing Query Parameters with Arrays and Objects
If your query parameters contain complex data structures like arrays or objects, you can use libraries like qs
to parse them.
Example with Arrays
app.get('/products', (req, res) => {
const filters = req.query.filters; // Filters can be passed as an array
res.send(`Filters: ${filters}`);
});
For a request to http://localhost:3000/products?filters=size&filters=color
, the response will be:
Filters: size,color
To handle more complex structures (like objects), you might need a parsing library, as Express's default behavior is limited to simple key-value pairs.
Example: Pagination with Query Parameters
A common use case is pagination, where clients pass parameters like page
and limit
to fetch specific pages of results.
app.get('/products', (req, res) => {
const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit) || 10;
const offset = (page - 1) * limit;
res.send(`Page: ${page}, Limit: ${limit}, Offset: ${offset}`);
});
For a request to http://localhost:3000/products?page=2&limit=5
, the response will be:
Page: 2, Limit: 5, Offset: 5
Summary of Accessing Query Parameters
Accessing a Single Parameter:
const param = req.query.paramName;
Handling Multiple Parameters:
const { param1, param2 } = req.query;
Default Values for Parameters:
const param = req.query.paramName || 'defaultValue';
Handling Arrays: Query parameters passed multiple times will be automatically parsed into arrays:
const arrayParam = req.query.paramName; // ['value1', 'value2']