body-parser: Node.js Body Parsing Middleware

2.2.2 · active · verified Sat Apr 18

body-parser is a Node.js middleware for parsing incoming request bodies, making them available under the `req.body` property in web frameworks like Express. It supports JSON, URL-encoded forms, raw buffers, and plain text, but explicitly does not handle multipart form data. The current stable version is 2.2.2, with active development and maintenance occurring across both the v1.x and v2.x major release lines.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to integrate `body-parser` into an Express application to parse incoming JSON and URL-encoded request bodies, making the parsed data available on `req.body`.

import express from 'express';
import bodyParser from 'body-parser';

const app = express();
const port = process.env.PORT ?? 3000;

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

// Middleware to parse URL-encoded bodies (e.g., from HTML forms)
// 'extended: true' allows parsing of rich objects and arrays from URL-encoded data
app.use(bodyParser.urlencoded({ extended: true }));

// Example POST endpoint to receive data
app.post('/api/data', (req, res) => {
  console.log('Received body:', req.body);
  // req.body contains the parsed data based on Content-Type
  res.json({ message: 'Data received successfully!', data: req.body });
});

// Start the server
app.listen(port, () => {
  console.log(`Server listening on port ${port}`);
});

view raw JSON →