body-parser middleware

Node.js body parsing middleware

ハンドラの前に入ってくるリクエストボディをミドルウェアで解析し、req.bodyプロパティで を利用できます。

注意 req. odyの形状はユーザーが制御する入力に基づいており、このオブジェクト内のすべての プロパティと値は信頼できず、信頼する前に 検証する必要があります。 For example, req.body.foo.toString() may fail in multiple ways, for example the foo property may not be there or may not be a string, and toString may not be a function and instead a string or other user input.

Learn about the anatomy of an HTTP transaction in Node.js.

これは複合体であり、通常は 大きな性質のため、マルチパートbodyを扱いません。マルチパートボディの場合、以下の モジュールに興味があるかもしれません。

このモジュールは以下のパーサを提供します。

All parsers support automatic inflation of gzip, br (brotli), deflate and zstd encodings. zstd is available in Node.js ^22.15.0 and >=23.8.0.

あなたが興味を持っているかもしれない他のボディパーサ:

インストール

Terminal window
npm install body-parser

body-parser does not include its own TypeScript type definitions. If you use TypeScript, also install the community-maintained types from DefinitelyTyped as a development dependency:

Terminal window
npm install --save-dev @types/body-parser

API

// Import all parsers
const bodyParser = require('body-parser');
// Or import individual parsers directly
const json = require('body-parser/json');
const urlencoded = require('body-parser/urlencoded');
const raw = require('body-parser/raw');
const text = require('body-parser/text');

bodyParser オブジェクトは、ミドルウェアを作成するために様々な工場を公開します。 All middlewares will populate the req.body property with the parsed body when the Content-Type request header matches the type option.

Note As of v2, req.body is left undefined when no body is parsed (for example when the request has neither Content-Length nor Transfer-Encoding, or when Content-Type does not match). In v1, req.body was always initialized to {}. Code that assumes req.body is always an object should use optional chaining (for example req.body?.username) or set a default.

このモジュールによって返される様々なエラーは、 errors sectionで説明されています。

bodyParser.json([options])

Returns middleware that only parses json and only looks at requests where the Content-Type header matches the type option. This parser accepts any Unicode encoding of the body.

ミドルウェアの後に request オブジェクトに解析されたデータを含む新しいbody オブジェクトが追加されました。

オプション

The json function takes an optional options object that may contain any of the following keys:

defaultCharset

リクエストの Content-Type ヘッダーに文字セットが 指定されていない場合、json コンテンツのデフォルト文字セットを指定します。デフォルトは utf-8 です。

膨らませ

true に設定されている場合、デフレートされた(圧縮された)ボディは膨らまれます。 false の場合、デフレートされたボディは拒否されます。デフォルトは true です。

制限

リクエストボディの最大サイズを制御します。これが数値の場合、値 はバイト数を指定します。 文字列であれば、値はbytes ライブラリに渡され、解析します。デフォルト は '100kb' です。

可能な限り高い制限を設定し、可能な限りデフォルト値を使用しないことをお勧めします。より大きなペイロードを許可すると、デコードと変換に必要なリソースのため、メモリ使用量が増加します。 より多くのデータが処理されるにつれて応答時間が長くなることもあります「非常に高い」とは、例えば5MB以上のペイロードなど、デフォルトよりも高い値を意味しますが、既にこれらのリスクを導入し始めています。デフォルトの制限では、これらの問題は発生しません。

reviver

2番目の 引数としてリバイバーオプションは直接JSON.parseに渡されます。 You can find more information on this argument in the MDN documentation about JSON.parse.

厳格な

When set to true, it will only accept arrays and objects; when false, it will accept anything JSON.parse accepts. デフォルトは true です。

タイプ

type オプションは、ミドルウェアが 解析するメディアタイプを決定するために使用されます。このオプションは文字列、文字列の配列、または関数です。 If not a function, type option is passed directly to the type-is library and this can be an extension name (like json), a mime type (like application/json), or a mime type with a wildcard (like */* or */json). 関数の場合、type オプションはfn(req)と呼ばれ、リクエストは真の 値を返した場合に解析されます。デフォルトは application/json です。

確認する

verify オプションを指定すると、verify(req, res, buf, encoding)と呼ばれます。 で、 buf は生のリクエストボディの Buffer で、 encoding はリクエストの エンコーディングです。エラーを投げることで解析を中止することができます。

bodyParser.raw([options])

全ての本文をBufferとして解析し、Content-Typeヘッダーがtypeオプションにマッチする リクエストのみを参照するミドルウェアを返します。

ミドルウェアの後に request オブジェクトに解析されたデータを含む新しいbody オブジェクトが追加されました。これは本文の Buffer オブジェクト になります。

オプション

The raw function takes an optional options object that may contain any of the following keys:

膨らませ

true に設定されている場合、デフレートされた(圧縮された)ボディは膨らまれます。 false の場合、デフレートされたボディは拒否されます。デフォルトは true です。

制限

リクエストボディの最大サイズを制御します。これが数値の場合、値 はバイト数を指定します。 文字列であれば、値はbytes ライブラリに渡され、解析します。デフォルト は '100kb' です。

可能な限り高い制限を設定し、可能な限りデフォルト値を使用しないことをお勧めします。より大きなペイロードを許可すると、デコードと変換に必要なリソースのため、メモリ使用量が増加します。 より多くのデータが処理されるにつれて応答時間が長くなることもあります「非常に高い」とは、例えば5MB以上のペイロードなど、デフォルトよりも高い値を意味しますが、既にこれらのリスクを導入し始めています。デフォルトの制限では、これらの問題は発生しません。

タイプ

type オプションは、ミドルウェアが 解析するメディアタイプを決定するために使用されます。このオプションは文字列、文字列の配列、または関数です。 If not a function, type option is passed directly to the type-is library and this can be an extension name (like bin), a mime type (like application/octet-stream), or a mime type with a wildcard (like */* or application/*). 関数の場合、type オプションは fn(req) と呼ばれ、リクエストは真の値を返す場合に解析されます。デフォルトは application/octet-stream です。

確認する

verify オプションを指定すると、verify(req, res, buf, encoding)と呼ばれます。 で、 buf は生のリクエストボディの Buffer で、 encoding はリクエストの エンコーディングです。エラーを投げることで解析を中止することができます。

bodyParser.text([options])

全ての本文を文字列として解析し、Content-Typeヘッダーがtypeオプションにマッチする リクエストのみを参照するミドルウェアを返します。

A new body string containing the parsed data is populated on the request object after the middleware (i.e. req.body). This will be a string of the body.

オプション

The text function takes an optional options object that may contain any of the following keys:

defaultCharset

Specify the default character set for the text content if the charset is not specified in the Content-Type header of the request. デフォルトは utf-8 です。

膨らませ

true に設定されている場合、デフレートされた(圧縮された)ボディは膨らまれます。 false の場合、デフレートされたボディは拒否されます。デフォルトは true です。

制限

リクエストボディの最大サイズを制御します。これが数値の場合、値 はバイト数を指定します。 文字列であれば、値はbytes ライブラリに渡され、解析します。デフォルト は '100kb' です。

可能な限り高い制限を設定し、可能な限りデフォルト値を使用しないことをお勧めします。より大きなペイロードを許可すると、デコードと変換に必要なリソースのため、メモリ使用量が増加します。 より多くのデータが処理されるにつれて応答時間が長くなることもあります「非常に高い」とは、例えば5MB以上のペイロードなど、デフォルトよりも高い値を意味しますが、既にこれらのリスクを導入し始めています。デフォルトの制限では、これらの問題は発生しません。

タイプ

type オプションは、ミドルウェアが 解析するメディアタイプを決定するために使用されます。このオプションは文字列、文字列の配列、または関数です。 If not a function, type option is passed directly to the type-is library and this can be an extension name (like txt), a mime type (like text/plain), or a mime type with a wildcard (like */* or text/*). If a function, the type option is called as fn(req) and the request is parsed if it returns a truthy value. Defaults to text/plain.

確認する

verify オプションを指定すると、verify(req, res, buf, encoding)と呼ばれます。 で、 buf は生のリクエストボディの Buffer で、 encoding はリクエストの エンコーディングです。エラーを投げることで解析を中止することができます。

bodyParser.urlencoded([options])

Returns middleware that only parses urlencoded bodies and only looks at requests where the Content-Type header matches the type option. This parser accepts only UTF-8 and ISO-8859-1 encodings of the body.

ミドルウェアの後に request オブジェクトに解析されたデータを含む新しいbody オブジェクトが追加されました。 This object will contain key-value pairs, where the value can be a string or array (when extended is false), or any type (when extended is true).

オプション

The urlencoded function takes an optional options object that may contain any of the following keys:

extended

The “extended” syntax allows for rich objects and arrays to be encoded into the URL-encoded format, allowing for a JSON-like experience with URL-encoded. For more information, please see the qs library.

Defaults to false.

膨らませ

true に設定されている場合、デフレートされた(圧縮された)ボディは膨らまれます。 false の場合、デフレートされたボディは拒否されます。デフォルトは true です。

制限

リクエストボディの最大サイズを制御します。これが数値の場合、値 はバイト数を指定します。 文字列であれば、値はbytes ライブラリに渡され、解析します。デフォルト は '100kb' です。

可能な限り高い制限を設定し、可能な限りデフォルト値を使用しないことをお勧めします。より大きなペイロードを許可すると、デコードと変換に必要なリソースのため、メモリ使用量が増加します。 より多くのデータが処理されるにつれて応答時間が長くなることもあります「非常に高い」とは、例えば5MB以上のペイロードなど、デフォルトよりも高い値を意味しますが、既にこれらのリスクを導入し始めています。デフォルトの制限では、これらの問題は発生しません。

parameterLimit

The parameterLimit option controls the maximum number of parameters that are allowed in the URL-encoded data. If a request contains more parameters than this value, a 413 will be returned to the client. Defaults to 1000.

タイプ

type オプションは、ミドルウェアが 解析するメディアタイプを決定するために使用されます。このオプションは文字列、文字列の配列、または関数です。 If not a function, type option is passed directly to the type-is library and this can be an extension name (like urlencoded), a mime type (like application/x-www-form-urlencoded), or a mime type with a wildcard (like */x-www-form-urlencoded). If a function, the type option is called as fn(req) and the request is parsed if it returns a truthy value. Defaults to application/x-www-form-urlencoded.

確認する

verify オプションを指定すると、verify(req, res, buf, encoding)と呼ばれます。 で、 buf は生のリクエストボディの Buffer で、 encoding はリクエストの エンコーディングです。エラーを投げることで解析を中止することができます。

defaultCharset

The default charset to parse as, if not specified in content-type. Must be either utf-8 or iso-8859-1. デフォルトは utf-8 です。

charsetSentinel

Whether to let the value of the utf8 parameter take precedence as the charset selector. It requires the form to contain a parameter named utf8 with a value of ✓. Defaults to false.

interpretNumericEntities

Whether to decode numeric entities such as ☺ when parsing an iso-8859-1 form. Defaults to false.

depth

The depth option is used to configure the maximum depth of the qs library when extended is true. This allows you to limit the amount of keys that are parsed and can be useful to prevent certain types of abuse. Defaults to 32. It is recommended to keep this value as low as possible.

Errors

The middlewares provided by this module create errors using the http-errors module. The errors will typically have a status/statusCode property that contains the suggested HTTP response code, an expose property to determine if the message property should be displayed to the client, a type property to determine the type of error without matching against the message, and a body property containing the read body, if available.

The following are the common errors created, though any error can come through for various reasons.

content encoding unsupported

This error will occur when the request had a Content-Encoding header that contained an encoding but the “inflation” option was set to false. The status property is set to 415, the type property is set to 'encoding.unsupported', and the charset property will be set to the encoding that is unsupported.

entity parse failed

This error will occur when the request contained an entity that could not be parsed by the middleware. The status property is set to 400, the type property is set to 'entity.parse.failed', and the body property is set to the entity value that failed parsing.

entity verify failed

This error will occur when the request contained an entity that could not be verified by the defined verify option. The status property is set to 403, the type property is set to 'entity.verify.failed', and the body property is set to the entity value that failed verification.

request aborted

This error will occur when the request is aborted by the client before reading the body has finished. The received property will be set to the number of bytes received before the request was aborted and the expected property is set to the number of expected bytes. The status property is set to 400 and type property is set to 'request.aborted'.

request entity too large

This error will occur when the request body’s size is larger than the “limit” option. The limit property will be set to the byte limit and the length property will be set to the request body’s length. The status property is set to 413 and the type property is set to 'entity.too.large'.

request size did not match content length

This error will occur when the request’s length did not match the length from the Content-Length header. This typically occurs when the request is malformed, typically when the Content-Length header was calculated based on characters instead of bytes. The status property is set to 400 and the type property is set to 'request.size.invalid'.

stream encoding should not be set

This error will occur when something called the req.setEncoding method prior to this middleware. This module operates directly on bytes only and you cannot call req.setEncoding when using this module. The status property is set to 500 and the type property is set to 'stream.encoding.set'.

stream is not readable

This error will occur when the request is no longer readable when this middleware attempts to read it. This typically means something other than a middleware from this module read the request body already and the middleware was also configured to read the same request. The status property is set to 500 and the type property is set to 'stream.not.readable'.

too many parameters

This error will occur when the content of the request exceeds the configured parameterLimit for the urlencoded parser. The status property is set to 413 and the type property is set to 'parameters.too.many'.

unsupported charset “BOGUS”

This error will occur when the request had a charset parameter in the Content-Type header, but the iconv-lite module does not support it OR the parser does not support it. The charset is contained in the message as well as in the charset property. The status property is set to 415, the type property is set to 'charset.unsupported', and the charset property is set to the charset that is unsupported.

unsupported content encoding “bogus”

This error will occur when the request had a Content-Encoding header that contained an unsupported encoding. The encoding is contained in the message as well as in the encoding property. The status property is set to 415, the type property is set to 'encoding.unsupported', and the encoding property is set to the encoding that is unsupported.

The input exceeded the depth

This error occurs when using bodyParser.urlencoded with the extended property set to true and the input exceeds the configured depth option. The status property is set to 400. It is recommended to review the depth option and evaluate if it requires a higher value. With the default depth of 32, an input with 33 or more levels of nesting gets this error.

例

Express/Connect top-level generic

This example demonstrates adding a generic JSON and URL-encoded parser as a top-level middleware, which will parse the bodies of all incoming requests. This is the simplest setup.

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded());
// 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(String(JSON.stringify(req.body, null, 2)));
});

Express route-specific

This example demonstrates adding body parsers specifically to the routes that need them. In general, this is the most recommended way to use body-parser with Express.

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
// create application/json parser
const jsonParser = bodyParser.json();
// create application/x-www-form-urlencoded parser
const urlencodedParser = bodyParser.urlencoded();
// POST /login gets urlencoded bodies
app.post('/login', urlencodedParser, function (req, res) {
if (!req.body || !req.body.username) res.sendStatus(400);
res.send('welcome, ' + req.body.username);
});
// POST /api/users gets JSON bodies
app.post('/api/users', jsonParser, function (req, res) {
if (!req.body) res.sendStatus(400);
// create user in req.body
});

Change accepted type for parsers

All the parsers accept a type option which allows you to change the Content-Type that the middleware will parse.

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
// 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' }));

ライセンス

MIT