Topic 41 of 55
req.query
Overview
Query strings are the part of a URL that comes after a question mark `?` (e.g., `?sort=asc&page=2`). They are typically used for filtering, sorting, or paginating data. Express parses them automatically into the `req.query` object.
Syntax
javascript
// URL: /search?term=laptop&maxPrice=1500&inStock=true
app.get('/search', (req, res) => {
// Express automatically parses the query string
console.log(req.query);
/*
{
term: 'laptop',
maxPrice: '1500',
inStock: 'true'
}
*/
const searchTerm = req.query.term;
res.send(`Searching for ${searchTerm}`);
});Common Pitfalls
- Like `req.params`, everything in `req.query` is a string. `?isAdmin=true` results in the string `'true'`, not a boolean.
- A query parameter can be an array if provided multiple times! `?color=red&color=blue` results in `req.query.color === ['red', 'blue']`. Your code must handle both string and array possibilities if users manipulate the URL.
Real-World Example
Implementing pagination and sorting in an API:
example
javascript
app.get('/api/products', async (req, res) => {
// Set default values if query parameters aren't provided
const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit) || 20;
const sortBy = req.query.sort || 'createdAt';
const order = req.query.order === 'desc' ? -1 : 1;
// Calculate skip for database pagination
const skip = (page - 1) * limit;
// Fetch from database
const products = await db.collection('products')
.find()
.sort({ [sortBy]: order })
.skip(skip)
.limit(limit)
.toArray();
res.json({
page,
limit,
count: products.length,
data: products
});
});