In Express.js, a popular Node.js web framework, req
is an object that represents the HTTP request. It has several properties that allow you to access data sent with the request. Here's a breakdown of the differences between req.body
, req.query
, and req.params
:
req.body
- Contains the parsed body of the request, typically used for POST, PUT, and PATCH requests.
- The body can be in various formats, such as JSON, URL-encoded, or multipart/form-data.
- To access
req.body
, you need to use a middleware likebody-parser
orexpress.json()
.
req.query
- Contains the query string parameters of the request, typically used for GET requests.
- The query string is the part of the URL that comes after the
?
symbol. -
req.query
is an object where the keys are the parameter names and the values are the parameter values.
req.params
- Contains the route parameters of the request, typically used for routes with parameterized paths.
- Route parameters are defined in the route path using a colon (
:
) followed by the parameter name. -
req.params
is an object where the keys are the parameter names and the values are the parameter values.
Here's an example to illustrate the differences:
const express = require('express');
const app = express();
app.use(express.json());
// Route with route parameter
app.get('/users/:id', (req, res) => {
console.log(req.params); // { id: '123' }
res.send(`User ID: ${req.params.id}`);
});
// Route with query string parameters
app.get('/products', (req, res) => {
console.log(req.query); // { category: 'electronics', price: '100' }
res.send(`Products: ${req.query.category} ${req.query.price}`);
});
// Route with request body
app.post('/orders', (req, res) => {
console.log(req.body); // { productId: '123', quantity: 2 }
res.send(`Order placed: ${req.body.productId} x ${req.body.quantity}`);
});
This code