Understanding req.params, req.query, and req.body in Express

Inder Rajoriya - Sep 24 - - Dev Community

Radhe Radhe Guy's

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 the request body:

  • Using curl:
  curl -d '{"key1":"value1", "key2":"value2"}' -H "Content-Type: application/json" -X POST http://localhost:3000/inder
Enter fullscreen mode Exit fullscreen mode
  • Using axios:
  axios.post('/inder', {
    key1: 'value1',
    key2: 'value2'
  })
  .then(response => {
    // handle response
  })
  .catch(error => {
    // handle error
  });
Enter fullscreen mode Exit fullscreen mode

How to access data from req.body:

app.post('/inder', (req, res) => {
  console.log(req.body.key1); // Output: value1
  console.log(req.body.key2); // Output: value2
});
Enter fullscreen mode Exit fullscreen mode

Remember: You need to use the express.json() middleware to parse JSON bodies.

app.use(express.json());
Enter fullscreen mode Exit fullscreen mode

2. req.params

This is used for named route parameters, which are part of the URL path.
Route parameters are great for passing data in dynamic routes, such as IDs or resource names.

Example:

app.get('/inder/:number', (req, res) => {
  console.log(req.params.number); // Outputs the value of `number` from the URL
});
Enter fullscreen mode Exit fullscreen mode

Client request:

GET http://localhost:3000/inder/1
Enter fullscreen mode Exit fullscreen mode

3. req.query

req.query is commonly used for querying/filtering data, like pagination, sorting, or filtering API responses. It's passed as key-value pairs in the URL.

Example:

app.get('/animals', (req, res) => {
  console.log(req.query.page); // Output: 10
});
Enter fullscreen mode Exit fullscreen mode

Client request:

GET http://localhost:3000/animals?page=10
Enter fullscreen mode Exit fullscreen mode

Each of these properties has a specific use case and is essential for managing different types of client-server communication in Express.

Thanks for reading! 🤍🤞🏻

.
Terabox Video Player