0
0
Node.jsframework~5 mins

Parsing request body (JSON and form data) in Node.js

Choose your learning style9 modes available
Introduction

When a user sends data to your server, you need to read it. Parsing the request body means turning that data into something your code can use easily.

When a user submits a form on a website and you want to get their input.
When your server receives JSON data from a mobile app or frontend.
When you want to handle file uploads or form submissions.
When you build APIs that accept data from clients.
When you need to process user input to save it or respond accordingly.
Syntax
Node.js
import express from 'express';
const app = express();

// To parse JSON data
app.use(express.json());

// To parse URL-encoded form data
app.use(express.urlencoded({ extended: true }));

app.post('/submit', (req, res) => {
  const data = req.body;
  res.send(data);
});

express.json() reads JSON data sent in the request body.

express.urlencoded() reads form data sent as URL-encoded (like from HTML forms).

Examples
This line tells Express to automatically read JSON data from incoming requests.
Node.js
app.use(express.json());
This line tells Express to read form data sent with the content type application/x-www-form-urlencoded.
Node.js
app.use(express.urlencoded({ extended: true }));
This route reads the parsed data from req.body and sends a response.
Node.js
app.post('/data', (req, res) => {
  console.log(req.body);
  res.send('Got your data!');
});
Sample Program

This simple Express server listens on port 3000. It can accept POST requests with JSON or form data at the /submit route. It sends back the data it received as JSON.

Node.js
import express from 'express';

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

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

// Middleware to parse form data
app.use(express.urlencoded({ extended: true }));

app.post('/submit', (req, res) => {
  // req.body contains parsed data
  res.json({ receivedData: req.body });
});

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

Always use these middleware before your routes to ensure req.body is populated.

For JSON, the client must send the header Content-Type: application/json.

For form data, the client sends Content-Type: application/x-www-form-urlencoded.

Summary

Parsing request body lets your server understand data sent by users or apps.

Use express.json() for JSON data and express.urlencoded() for form data.

Access the parsed data in your route handlers via req.body.