In Express.js, the request object (req
) contains three important properties: req.params
, req.query
, and req.body
. These properties are essential for handling data sent from the client to the server. This post highlights the differences between them and provides examples of their usage.
1. req.body
This property is typically used in POST or PUT requests. It is ideal for transmitting sensitive data, such as form submissions or extensive JSON objects.
Sending Data in the Request Body
Using CURL:
curl -d '{"key1":"value1", "key2":"value2"}' -H "Content-Type: application/json" -X POST http://localhost:3000/inder
Using Axios:
axios.post('/inder', {
key1: 'value1',
key2: 'value2'
})
.then(response => {
// Handle response
})
.catch(error => {
// Handle error
});
Retrieving Data from the Request Body:
app.post('/inder', (req, res) => {
console.log(req.body.key1); // Output: value1
console.log(req.body.key2); // Output: value2
});
Ensure to include the express.json()
middleware to parse the request body; otherwise, an error may occur:
app.use(express.json());
2. req.params
This property contains named route parameters attached to the URL. To define these parameters, prefix the name with a colon (:
) in your route definitions.
Example:
app.get('/inder/:number', (req, res) => {
console.log(req.params.number); // Accesses the 'number' parameter
});
To send the parameter from the client, replace its name in the URL with the desired value:
GET http://localhost:3000/inder/1
3. req.query
req.query
is predominantly used for operations like searching, sorting, filtering, and pagination. For instance, if you want to retrieve data from a specific page, this is the property you'd utilize. Query strings are typically formatted as key=value
.
Example:
GET http://localhost:3000/animals?page=10
Accessing Query Parameters in Express:
app.get('/animals', (req, res) => {
console.log(req.query.page); // Output: 10
});
Conclusion
I hope this breakdown clarifies how to use req.body
, req.params
, and req.query
in your Express applications. Understanding these properties will enhance your ability to handle client-server interactions effectively.
Thanks for reading! 🤍🤞🏻
Top comments (0)