0
0
Expressframework~5 mins

req.body for request payload in Express

Choose your learning style9 modes available
Introduction

We use req.body to get the data sent by a user in a web form or API call. It helps the server understand what the user wants to send.

When a user submits a form with information like name or email.
When an app sends data to the server to create or update something.
When you want to read JSON data sent from a client app.
When handling file uploads or other data sent in the request body.
When building APIs that accept data from other programs.
Syntax
Express
app.post('/path', (req, res) => {
  const data = req.body;
  // use data here
  res.send('Got your data');
});

You need to use middleware like express.json() to parse JSON data before accessing req.body.

req.body contains the data sent by the client in the request payload.

Examples
This example shows how to read JSON data sent in a POST request.
Express
app.use(express.json());

app.post('/submit', (req, res) => {
  console.log(req.body);
  res.send('Received');
});
This example reads form data sent as URL-encoded, like from an HTML form.
Express
app.use(express.urlencoded({ extended: true }));

app.post('/form', (req, res) => {
  console.log(req.body.name);
  res.send(`Hello, ${req.body.name}`);
});
Sample Program

This server listens for POST requests at /greet. It reads the name from req.body and sends a greeting. If no name is sent, it returns an error.

Express
import express from 'express';

const app = express();
const port = 3000;

// Middleware to parse JSON body
app.use(express.json());

app.post('/greet', (req, res) => {
  const { name } = req.body;
  if (name) {
    res.send(`Hello, ${name}!`);
  } else {
    res.status(400).send('Name is missing');
  }
});

app.listen(port, () => {
  console.log(`Server running on http://localhost:${port}`);
});
OutputSuccess
Important Notes

Always use express.json() or other body parsers before accessing req.body.

If you forget the middleware, req.body will be undefined.

For security, validate and sanitize data from req.body before using it.

Summary

req.body holds the data sent by the client in the request payload.

You must use middleware like express.json() to read JSON data.

Use req.body to get user input from forms or API calls.