Node.js(Express): req.body vs req.params vs req.query

Deepak Chaudhari
2 min readJun 19, 2024

--

In Node.js with Express, req.body, req.params, and req.query are all properties of the req (request) object that contain data sent from the client (usually a web browser) to the server. However, they differ in where that data comes from in the request:

1. req.body:

  • Contains data submitted using HTTP methods like POST, PUT, or PATCH.
  • This data is typically sent in the request body format like JSON or form-encoded data.
  • To access req.body, you usually need to use a middleware like body-parser to parse the request body and populate the object.

Example:

const express = require('express');
const bodyParser = require('body-parser'); // Middleware for parsing req.body

const app = express();
app.use(bodyParser.json()); // Use middleware to parse JSON data

app.post('/users', (req, res) => {
const { name, email } = req.body; // Access data from req.body
console.log(`New user: ${name} - ${email}`);
res.send('User created successfully!');
});
  • ontains data from dynamic parts of the URL, often used for routing purposes.
  • These dynamic parts are denoted by colons (:) in the route definition.

Example:

app.get('/users/:id', (req, res) => {
const userId = req.params.id; // Access data from req.params
console.log(`Get user with ID: ${userId}`);
res.send(`User with ID ${userId} retrieved!`);
});

3. req.query:

  • Contains data sent as query parameters appended to the URL after a question mark (?).
  • These parameters are used to filter, search, or paginate data.

Example:

app.get('/products', (req, res) => {
const category = req.query.category; // Access data from req.query
console.log(`Filter products by category: ${category}`);
res.send(`Products in category ${category} fetched!`);
});

In summary:

  • Use req.body for data submitted in the request body.
  • Use req.params for dynamic URL segments.
  • Use req.query for query string parameters.

By understanding these differences, you can effectively retrieve and handle data sent from the client in your Node.js applications using Express.

=============================+ Thank You !!!+==============================
Note: Don’t forget to follow and give 50 claps.👏 👏 👏

--

--