Security News
ESLint is Now Language-Agnostic: Linting JSON, Markdown, and Beyond
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
body-parser
Advanced tools
The body-parser package is a Node.js middleware that parses incoming request bodies before your handlers, available under the req.body property. It is commonly used to parse JSON, raw, text, and URL-encoded form data.
JSON Body Parsing
This feature allows the server to accept and parse incoming requests with JSON payloads, making the parsed data available under req.body.
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.post('/json', (req, res) => {
res.send(req.body);
});
URL-Encoded Form Data Parsing
This feature is used to parse payloads from forms submitted via HTTP POST. The 'extended' option allows for rich objects and arrays to be encoded into the URL-encoded format, allowing for a JSON-like experience with URL-encoded forms.
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/form', (req, res) => {
res.send(req.body);
});
Raw Body Parsing
This feature lets the server accept raw data in the request body, useful for parsing bodies that are not text-based, like binary data streams.
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }));
app.post('/raw', (req, res) => {
res.send(req.body);
});
Text Body Parsing
This feature allows parsing text bodies, such as plain text or HTML, from the request body.
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.text({ type: 'text/html' }));
app.post('/text', (req, res) => {
res.send(req.body);
});
Multer is a middleware for handling 'multipart/form-data', primarily used for uploading files. It is different from body-parser as it is specialized for file upload scenarios.
Formidable is a Node.js module for parsing form data, especially file uploads. It can handle multiple file uploads and supports file size limits, making it more feature-rich for handling forms than body-parser.
Busboy is a streaming parser for HTML form data for Node.js. It is faster and more efficient for large file uploads compared to body-parser, which does not handle file streams.
Designed for the Koa framework, koa-body is a full-featured body parser middleware. It supports multipart, urlencoded, and json request bodies and provides additional features like file uploads, making it a more comprehensive solution than body-parser for Koa applications.
Node.js body parsing middleware.
This does not handle multipart bodies, due to their complex and typically large nature. For multipart bodies, you may be interested in the following modules:
Other body parsers you might be interested in:
$ npm install body-parser
var bodyParser = require('body-parser')
Returns middleware that only parses json
. This parser accepts any Unicode encoding of the body and supports automatic inflation of gzip
and deflate
encodings.
The options are:
strict
- only parse objects and arrays. (default: true
)inflate
- if deflated bodies will be inflated. (default: true
)limit
- maximum request body size. (default: <100kb>
)reviver
- passed to JSON.parse()
type
- request content-type to parse (default: json
)verify
- function to verify body contentThe type
argument is passed directly to the type-is library. This can be an extension name (like json
), a mime type (like application/json
), or a mime time with a wildcard (like */json
).
The verify
argument, if supplied, is called as verify(req, res, buf, encoding)
, where buf
is a Buffer
of the raw request body and encoding
is the encoding of the request. The parsing can be aborted by throwing an error.
The reviver
argument is passed directly to JSON.parse
as the second argument. You can find more information on this argument in the MDN documentation about JSON.parse.
Returns middleware that parses all bodies as a Buffer
. This parser supports automatic inflation of gzip
and deflate
encodings.
The options are:
inflate
- if deflated bodies will be inflated. (default: true
)limit
- maximum request body size. (default: <100kb>
)type
- request content-type to parse (default: application/octet-stream
)verify
- function to verify body contentThe type
argument is passed directly to the type-is library. This can be an extension name (like bin
), a mime type (like application/octet-stream
), or a mime time with a wildcard (like application/*
).
The verify
argument, if supplied, is called as verify(req, res, buf, encoding)
, where buf
is a Buffer
of the raw request body and encoding
is the encoding of the request. The parsing can be aborted by throwing an error.
Returns middleware that parses all bodies as a string. This parser supports automatic inflation of gzip
and deflate
encodings.
The options are:
defaultCharset
- the default charset to parse as, if not specified in content-type. (default: utf-8
)inflate
- if deflated bodies will be inflated. (default: true
)limit
- maximum request body size. (default: <100kb>
)type
- request content-type to parse (default: text/plain
)verify
- function to verify body contentThe type
argument is passed directly to the type-is library. This can be an extension name (like txt
), a mime type (like text/plain
), or a mime time with a wildcard (like text/*
).
The verify
argument, if supplied, is called as verify(req, res, buf, encoding)
, where buf
is a Buffer
of the raw request body and encoding
is the encoding of the request. The parsing can be aborted by throwing an error.
Returns middleware that only parses urlencoded
bodies. This parser accepts only UTF-8 encoding of the body and supports automatic inflation of gzip
and deflate
encodings.
The options are:
extended
- parse extended syntax with the qs module. (default: true
, but using the default has been deprecated. Please research into the difference between qs
and querystring
and choose the appropriate setting)inflate
- if deflated bodies will be inflated. (default: true
)limit
- maximum request body size. (default: <100kb>
)parameterLimit
- maximum number of parameters. (default: 1000
)type
- request content-type to parse (default: urlencoded
)verify
- function to verify body contentThe extended
argument allows to choose between parsing the urlencoded data with the querystring
library (when false
) or the qs
library (when true
). The "extended" syntax allows for rich objects and arrays to be encoded into the urlencoded format, allowing for a JSON-like experience with urlencoded. For more information, please see the qs library.
The parameterLimit
argument controls the maximum number of parameters that are allowed in the urlencoded data. If a request contains more parameters than this value, a 413 will be returned to the client.
The type
argument is passed directly to the type-is library. This can be an extension name (like urlencoded
), a mime type (like application/x-www-form-urlencoded
), or a mime time with a wildcard (like */x-www-form-urlencoded
).
The verify
argument, if supplied, is called as verify(req, res, buf, encoding)
, where buf
is a Buffer
of the raw request body and encoding
is the encoding of the request. The parsing can be aborted by throwing an error.
A new body
object containing the parsed data is populated on the request
object after the middleware.
This example demonstrates adding a generic JSON and urlencoded parser as a top-level middleware, which will parse the bodies of all incoming requests. This is the simplest setup.
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.use(function (req, res) {
res.setHeader('Content-Type', 'text/plain')
res.write('you posted:\n')
res.end(JSON.stringify(req.body, null, 2))
})
This example demonstrates adding body parsers specifically to the routes that need them. In general, this is the most recommend way to use body-parser with express.
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// create application/json parser
var jsonParser = bodyParser.json()
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
// POST /login gets urlencoded bodies
app.post('/login', urlencodedParser, function (req, res) {
if (!req.body) return res.sendStatus(400)
res.send('welcome, ' + res.body.username)
})
// POST /api/users gets JSON bodies
app.post('/api/users', jsonParser, function (req, res) {
if (!req.body) return res.sendStatus(400)
// create user in req.body
})
All the parsers accept a type
option which allows you to change the Content-Type
that the middleware will parse.
// parse various different custom JSON types as JSON
app.use(bodyParser.json({ type: 'application/*+json' }))
// parse some custom thing into a Buffer
app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }))
// parse an HTML body into a string
app.use(bodyParser.text({ type: 'text/html' }))
FAQs
Node.js body parsing middleware
The npm package body-parser receives a total of 22,118,485 weekly downloads. As such, body-parser popularity was classified as popular.
We found that body-parser demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
Security News
Members Hub is conducting large-scale campaigns to artificially boost Discord server metrics, undermining community trust and platform integrity.
Security News
NIST has failed to meet its self-imposed deadline of clearing the NVD's backlog by the end of the fiscal year. Meanwhile, CVE's awaiting analysis have increased by 33% since June.