Express: req.params, req.query and req.body

gathoni

Mary Gathoni

Posted on September 5, 2020

Express: req.params, req.query and req.body

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
Enter fullscreen mode Exit fullscreen mode
  • using axios
  axios.post('/giraffe', {
    key1: 'value1',
    key2: 'value2'
  })
  .then(response => {
    ...
  })
  .catch(error => {
    ...
  })
Enter fullscreen mode Exit fullscreen mode

How to get data from request body

  app.get('/giraffe', (req, res) => {
   console.log(req.body.key1) //value1
   console.log(req.body.key2) //value2
  })
Enter fullscreen mode Exit fullscreen mode

Remember to use express.json() middleware to parse request body else you'll get an error

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

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)
  })
Enter fullscreen mode Exit fullscreen mode

To send the parameter from the client, just replace its name with the value

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

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
Enter fullscreen mode Exit fullscreen mode

To access this in your express server is pretty simple too;

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

I hope you found this helpful.

Thanks for reading 🥰.

Cover Photo by Adi Goldstein on Unsplash

💖 💪 🙅 🚩
gathoni
Mary Gathoni

Posted on September 5, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related