Beginner LevelExpress JS
What is the difference between req.params, req.query, and req.body?
❓ Interview Prompt: Compare URL path parameters (req.params), query strings (req.query), and request payload bodies (req.body).
Express extracts client data from three distinct locations in an HTTP request:
1. 'req.params' (URL Path Parameters):
•
Used to identify specific resources in dynamic route segments defined with a colon (':').
•
Route: '/api/users/:id/orders/:orderId'
•
URL: '/api/users/42/orders/99' $\rightarrow$ 'req.params = { id: "42", orderId: "99" }'
•
Note: Parameters are always parsed as strings!
2. 'req.query' (URL Query Strings):
•
Used for optional parameters like sorting, filtering, and pagination.
•
URL: '/api/products?category=books&limit=10&page=2'
•
Result: 'req.query = { category: "books", limit: "10", page: "2" }'
3. 'req.body' (HTTP Request Payload):
•
Used to send structured data (JSON, form submissions) in POST, PUT, or PATCH requests.
•
By default, Express does NOT parse request bodies! You must register a body-parsing middleware like 'express.json()' or 'express.urlencoded({ extended: true })' before route handlers, or 'req.body' will be 'undefined'.
Code Implementation Example
javascript
import express from 'express';
const app = express();
// Mandatory to populate req.body from JSON requests!
app.use(express.json());
// PUT /api/users/105/profile?notify=true
// Payload Body: { "email": "new@example.com", "age": 29 }
app.put('/api/users/:userId/profile', (req, res) => {
const userId = parseInt(req.params.userId, 10); // Path param: 105
const shouldNotify = req.query.notify === 'true'; // Query param: true
const { email, age } = req.body; // Body payload: "new@example.com", 29
res.json({
status: 'updated',
targetId: userId,
sentNotification: shouldNotify,
newData: { email, age }
});
});💡Extracting data from req.params, req.query, and req.body in Express.
🎯 Interview Key Takeaway
Use req.params for resource IDs, req.query for filtering/pagination, and req.body for POST/PUT payloads after adding express.json().
#req.params#req.query#req.body#Beginner
Back to all Express JS Questions→