These three, req.body, req.query and req.params are part of Express request object.
They are used by the client to send data to the server.
This post outlines their differences and gives examples on how to use them.
1. req.body
Generally used in POST/PUT requests.
Use it when you want to send sensitive data(eg. form data) or super long JSON data to the server.
How to send data in request body
- using curl
curl -d '{"key1":"value1", "key2":"value2"}' -H "ContentType: application/json" -X POST http://localhost:3000/giraffe
- using axios
axios.post('/giraffe', {
key1: 'value1',
key2: 'value2'
})
.then(response => {
...
})
.catch(error => {
...
})
How to get data from request body
app.get('/giraffe', (req, res) => {
console.log(req.body.key1) //value1
console.log(req.body.key2) //value2
})
Remember to use express.json() middleware to parse request body else you'll get an error
app.use(express.json())
2. req.params
These are properties attached to the url i.e named route parameters. You prefix the parameter name with a colon(:) when writing your routes.
For instance,
app.get('/giraffe/:number', (req, res) => {
console.log(req.params.number)
})
To send the parameter from the client, just replace its name with the value
GET http://localhost:3000/giraffe/1
3. req.query
req.query is mostly used for searching,sorting, filtering, pagination, e.t.c
Say for instance you want to query an API but only want to get data from page 10, this is what you'd generally use.
It written as key=value
GET http://localhost:3000/animals?page=10
To access this in your express server is pretty simple too;
app.get('/animals', ()=>{
console.log(req.query.page) // 10
})
I hope you found this helpful.
Thanks for reading 🥰.
Cover Photo by Adi Goldstein on Unsplash
Top comments (12)
Great article!
great
Easy explanation Great
Merci Mary
thanks
Thank you Mary! That was very useful. Great teaching style!
I would like to connect with you or follow you on LinkedIn but I cannot find your profile. Do you have one?
how to manage a request with a body and params (together)?
Good Post!
Amazing Explanation
Thanks