Query Parameters in Node.
js (Express)
1. What are Query Parameters?
Query parameters are extra information added to a URL to send data to the server without creating
multiple routes. They start after '?' in the URL. Format: key=value. Multiple parameters are
separated by '&'. Example: [Link] Here: q=node → search
keyword, page=2 → page number
2. Why Use Query Parameters?
We use them to: - Search: /search?q=shoes - Filter data:
/products?category=electronics&brand;=apple - Pagination: /products?page=2&limit;=10 - Sorting:
/news?sort=asc Instead of making multiple routes like /products/electronics/apple, we use one
route: /products?category=electronics&brand;=apple
3. How to Access Query Parameters in Express
[Link]('/search', (req, res) => {
[Link]([Link]); // { q: 'node', page: '2' }
[Link]([Link]);
});
URL: [Link]
4. Real-World Examples
- Amazon: [Link] - Netflix:
[Link] - News:
[Link]
5. Analogy
Restaurant Order Example: Main route: /order/pizza Query parameters: ?cheese=extra&onion;=no
Full URL: /order/pizza?cheese=extra&onion;=no
6. Solved Assignment Examples
const express = require('express');
const app = express();
const PORT = 3000;
// Products Route
[Link]('/products', (req, res) => {
const { category, brand, price } = [Link];
[Link](`Products → Category: ${category || 'Not provided'}, Brand: ${brand || 'Not provided'}, Price: ${price || 'Not p
});
// Movies Route
[Link]('/movies', (req, res) => {
const { genre, year } = [Link];
[Link](`Movies → Genre: ${genre || 'Not provided'}, Year: ${year || 'Not provided'}`);
});
// News Route
[Link]('/news', (req, res) => {
const { category, sort } = [Link];
[Link](`News → Category: ${category || 'Not provided'}, Sort: ${sort || 'Not provided'}`);
});
[Link](PORT, () => {
[Link](`Server running at [Link]
});
7. Summary
✔ Query Parameters = extra info in URL after '?' ✔ Format: key=value, multiple params joined with
'&' ✔ Access in Express using [Link] ✔ Commonly used for search, filter, pagination, sorting