req.query lets you get information sent in the URL after a question mark. This helps your app understand what the user wants without changing the page.
0
0
req.query for query strings in Express
Introduction
When you want to filter a list on a webpage, like showing only red shirts.
When you want to search for something using keywords typed in the URL.
When you want to control how many items show on a page, like 10 or 20.
When you want to remember user choices without saving them in a database.
When you want to pass small bits of data between pages without forms.
Syntax
Express
req.query.propertyName
req.query is an object containing all query string parameters as key-value pairs.
Each property corresponds to a parameter name in the URL.
Examples
This gets the 'term' from the URL like /search?term=books and shows it back.
Express
app.get('/search', (req, res) => { const term = req.query.term; res.send(`You searched for: ${term}`); });
This reads 'page' from the URL and uses 1 if none is given, like /items?page=3.
Express
app.get('/items', (req, res) => { const page = req.query.page || 1; res.send(`Page number: ${page}`); });
This reads multiple query parameters, like /filter?color=red&size=large.
Express
app.get('/filter', (req, res) => { const color = req.query.color; const size = req.query.size; res.send(`Filter by color: ${color}, size: ${size}`); });
Sample Program
This simple server listens on port 3000. When you visit /greet?name=Alice, it says 'Hello, Alice!'. If no name is given, it says 'Hello, Guest!'.
Express
import express from 'express'; const app = express(); const port = 3000; app.get('/greet', (req, res) => { const name = req.query.name || 'Guest'; res.send(`Hello, ${name}!`); }); app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); });
OutputSuccess
Important Notes
Query string values are always strings. Convert them if you need numbers.
If a query parameter is missing, its value will be undefined.
Use default values to avoid errors when parameters are missing.
Summary
req.query reads data sent in the URL after the question mark.
It helps your app respond differently based on user input in the URL.
Always check if query parameters exist before using them.