{"id":13396548,"url":"https://github.com/expressjs/body-parser","last_synced_at":"2025-05-12T16:26:30.081Z","repository":{"id":12990051,"uuid":"15669006","full_name":"expressjs/body-parser","owner":"expressjs","description":"Node.js body parsing middleware","archived":false,"fork":false,"pushed_at":"2025-05-04T10:38:23.000Z","size":639,"stargazers_count":5492,"open_issues_count":40,"forks_count":743,"subscribers_count":92,"default_branch":"master","last_synced_at":"2025-05-04T12:06:42.759Z","etag":null,"topics":["body","expressjs","javascript","json","middleware","nodejs","parser","urlencoded"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/expressjs.png","metadata":{"files":{"readme":"README.md","changelog":"HISTORY.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"open_collective":"express"}},"created_at":"2014-01-06T08:25:03.000Z","updated_at":"2025-05-04T10:38:19.000Z","dependencies_parsed_at":"2023-01-13T17:14:45.371Z","dependency_job_id":"18b5fb92-a77d-43d2-94d7-24ba844a4b20","html_url":"https://github.com/expressjs/body-parser","commit_stats":{"total_commits":680,"total_committers":35,"mean_commits":"19.428571428571427","dds":0.08235294117647063,"last_synced_commit":"80fbb762b1e326d9a7589df9285bf351d5685f35"},"previous_names":[],"tags_count":78,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/expressjs%2Fbody-parser","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/expressjs%2Fbody-parser/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/expressjs%2Fbody-parser/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/expressjs%2Fbody-parser/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/expressjs","download_url":"https://codeload.github.com/expressjs/body-parser/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252330723,"owners_count":21730690,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["body","expressjs","javascript","json","middleware","nodejs","parser","urlencoded"],"created_at":"2024-07-30T18:00:56.558Z","updated_at":"2025-05-04T12:06:49.896Z","avatar_url":"https://github.com/expressjs.png","language":"JavaScript","readme":"# body-parser\n\n[![NPM Version][npm-version-image]][npm-url]\n[![NPM Downloads][npm-downloads-image]][npm-url]\n[![Build Status][ci-image]][ci-url]\n[![Test Coverage][coveralls-image]][coveralls-url]\n[![OpenSSF Scorecard Badge][ossf-scorecard-badge]][ossf-scorecard-visualizer]\n\nNode.js body parsing middleware.\n\nParse incoming request bodies in a middleware before your handlers, available\nunder the `req.body` property.\n\n**Note** As `req.body`'s shape is based on user-controlled input, all\nproperties and values in this object are untrusted and should be validated\nbefore trusting. For example, `req.body.foo.toString()` may fail in multiple\nways, for example the `foo` property may not be there or may not be a string,\nand `toString` may not be a function and instead a string or other user input.\n\n[Learn about the anatomy of an HTTP transaction in Node.js](https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/).\n\n_This does not handle multipart bodies_, due to their complex and typically\nlarge nature. For multipart bodies, you may be interested in the following\nmodules:\n\n  * [busboy](https://www.npmjs.org/package/busboy#readme) and\n    [connect-busboy](https://www.npmjs.org/package/connect-busboy#readme)\n  * [multiparty](https://www.npmjs.org/package/multiparty#readme) and\n    [connect-multiparty](https://www.npmjs.org/package/connect-multiparty#readme)\n  * [formidable](https://www.npmjs.org/package/formidable#readme)\n  * [multer](https://www.npmjs.org/package/multer#readme)\n\nThis module provides the following parsers:\n\n  * [JSON body parser](#bodyparserjsonoptions)\n  * [Raw body parser](#bodyparserrawoptions)\n  * [Text body parser](#bodyparsertextoptions)\n  * [URL-encoded form body parser](#bodyparserurlencodedoptions)\n\nOther body parsers you might be interested in:\n\n- [body](https://www.npmjs.org/package/body#readme)\n- [co-body](https://www.npmjs.org/package/co-body#readme)\n\n## Installation\n\n```sh\n$ npm install body-parser\n```\n\n## API\n\n```js\nconst bodyParser = require('body-parser')\n```\n\nThe `bodyParser` object exposes various factories to create middlewares. All\nmiddlewares will populate the `req.body` property with the parsed body when\nthe `Content-Type` request header matches the `type` option.\n\nThe various errors returned by this module are described in the\n[errors section](#errors).\n\n### bodyParser.json([options])\n\nReturns middleware that only parses `json` and only looks at requests where\nthe `Content-Type` header matches the `type` option. This parser accepts any\nUnicode encoding of the body and supports automatic inflation of `gzip`,\n`br` (brotli) and `deflate` encodings.\n\nA new `body` object containing the parsed data is populated on the `request`\nobject after the middleware (i.e. `req.body`).\n\n#### Options\n\nThe `json` function takes an optional `options` object that may contain any of\nthe following keys:\n\n##### inflate\n\nWhen set to `true`, then deflated (compressed) bodies will be inflated; when\n`false`, deflated bodies are rejected. Defaults to `true`.\n\n##### limit\n\nControls the maximum request body size. If this is a number, then the value\nspecifies the number of bytes; if it is a string, the value is passed to the\n[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults\nto `'100kb'`.\n\n##### reviver\n\nThe `reviver` option is passed directly to `JSON.parse` as the second\nargument. You can find more information on this argument\n[in the MDN documentation about JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Example.3A_Using_the_reviver_parameter).\n\n##### strict\n\nWhen set to `true`, will only accept arrays and objects; when `false` will\naccept anything `JSON.parse` accepts. Defaults to `true`.\n\n##### type\n\nThe `type` option is used to determine what media type the middleware will\nparse. This option can be a string, array of strings, or a function. If not a\nfunction, `type` option is passed directly to the\n[type-is](https://www.npmjs.org/package/type-is#readme) library and this can\nbe an extension name (like `json`), a mime type (like `application/json`), or\na mime type with a wildcard (like `*/*` or `*/json`). If a function, the `type`\noption is called as `fn(req)` and the request is parsed if it returns a truthy\nvalue. Defaults to `application/json`.\n\n##### verify\n\nThe `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`,\nwhere `buf` is a `Buffer` of the raw request body and `encoding` is the\nencoding of the request. The parsing can be aborted by throwing an error.\n\n### bodyParser.raw([options])\n\nReturns middleware that parses all bodies as a `Buffer` and only looks at\nrequests where the `Content-Type` header matches the `type` option. This\nparser supports automatic inflation of `gzip`, `br` (brotli) and `deflate`\nencodings.\n\nA new `body` object containing the parsed data is populated on the `request`\nobject after the middleware (i.e. `req.body`). This will be a `Buffer` object\nof the body.\n\n#### Options\n\nThe `raw` function takes an optional `options` object that may contain any of\nthe following keys:\n\n##### inflate\n\nWhen set to `true`, then deflated (compressed) bodies will be inflated; when\n`false`, deflated bodies are rejected. Defaults to `true`.\n\n##### limit\n\nControls the maximum request body size. If this is a number, then the value\nspecifies the number of bytes; if it is a string, the value is passed to the\n[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults\nto `'100kb'`.\n\n##### type\n\nThe `type` option is used to determine what media type the middleware will\nparse. This option can be a string, array of strings, or a function.\nIf not a function, `type` option is passed directly to the\n[type-is](https://www.npmjs.org/package/type-is#readme) library and this\ncan be an extension name (like `bin`), a mime type (like\n`application/octet-stream`), or a mime type with a wildcard (like `*/*` or\n`application/*`). If a function, the `type` option is called as `fn(req)`\nand the request is parsed if it returns a truthy value. Defaults to\n`application/octet-stream`.\n\n##### verify\n\nThe `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`,\nwhere `buf` is a `Buffer` of the raw request body and `encoding` is the\nencoding of the request. The parsing can be aborted by throwing an error.\n\n### bodyParser.text([options])\n\nReturns middleware that parses all bodies as a string and only looks at\nrequests where the `Content-Type` header matches the `type` option. This\nparser supports automatic inflation of `gzip`, `br` (brotli) and `deflate`\nencodings.\n\nA new `body` string containing the parsed data is populated on the `request`\nobject after the middleware (i.e. `req.body`). This will be a string of the\nbody.\n\n#### Options\n\nThe `text` function takes an optional `options` object that may contain any of\nthe following keys:\n\n##### defaultCharset\n\nSpecify the default character set for the text content if the charset is not\nspecified in the `Content-Type` header of the request. Defaults to `utf-8`.\n\n##### inflate\n\nWhen set to `true`, then deflated (compressed) bodies will be inflated; when\n`false`, deflated bodies are rejected. Defaults to `true`.\n\n##### limit\n\nControls the maximum request body size. If this is a number, then the value\nspecifies the number of bytes; if it is a string, the value is passed to the\n[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults\nto `'100kb'`.\n\n##### type\n\nThe `type` option is used to determine what media type the middleware will\nparse. This option can be a string, array of strings, or a function. If not\na function, `type` option is passed directly to the\n[type-is](https://www.npmjs.org/package/type-is#readme) library and this can\nbe an extension name (like `txt`), a mime type (like `text/plain`), or a mime\ntype with a wildcard (like `*/*` or `text/*`). If a function, the `type`\noption is called as `fn(req)` and the request is parsed if it returns a\ntruthy value. Defaults to `text/plain`.\n\n##### verify\n\nThe `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`,\nwhere `buf` is a `Buffer` of the raw request body and `encoding` is the\nencoding of the request. The parsing can be aborted by throwing an error.\n\n### bodyParser.urlencoded([options])\n\nReturns middleware that only parses `urlencoded` bodies and only looks at\nrequests where the `Content-Type` header matches the `type` option. This\nparser accepts only UTF-8 encoding of the body and supports automatic\ninflation of `gzip`, `br` (brotli) and `deflate` encodings.\n\nA new `body` object containing the parsed data is populated on the `request`\nobject after the middleware (i.e. `req.body`). This object will contain\nkey-value pairs, where the value can be a string or array (when `extended` is\n`false`), or any type (when `extended` is `true`).\n\n#### Options\n\nThe `urlencoded` function takes an optional `options` object that may contain\nany of the following keys:\n\n##### extended\n\nThe \"extended\" syntax allows for rich objects and arrays to be encoded into the\nURL-encoded format, allowing for a JSON-like experience with URL-encoded. For\nmore information, please [see the qs\nlibrary](https://www.npmjs.org/package/qs#readme).\n\nDefaults to `false`.\n\n##### inflate\n\nWhen set to `true`, then deflated (compressed) bodies will be inflated; when\n`false`, deflated bodies are rejected. Defaults to `true`.\n\n##### limit\n\nControls the maximum request body size. If this is a number, then the value\nspecifies the number of bytes; if it is a string, the value is passed to the\n[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults\nto `'100kb'`.\n\n##### parameterLimit\n\nThe `parameterLimit` option controls the maximum number of parameters that\nare allowed in the URL-encoded data. If a request contains more parameters\nthan this value, a 413 will be returned to the client. Defaults to `1000`.\n\n##### type\n\nThe `type` option is used to determine what media type the middleware will\nparse. This option can be a string, array of strings, or a function. If not\na function, `type` option is passed directly to the\n[type-is](https://www.npmjs.org/package/type-is#readme) library and this can\nbe an extension name (like `urlencoded`), a mime type (like\n`application/x-www-form-urlencoded`), or a mime type with a wildcard (like\n`*/x-www-form-urlencoded`). If a function, the `type` option is called as\n`fn(req)` and the request is parsed if it returns a truthy value. Defaults\nto `application/x-www-form-urlencoded`.\n\n##### verify\n\nThe `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`,\nwhere `buf` is a `Buffer` of the raw request body and `encoding` is the\nencoding of the request. The parsing can be aborted by throwing an error.\n\n##### defaultCharset\n\nThe default charset to parse as, if not specified in content-type. Must be\neither `utf-8` or `iso-8859-1`. Defaults to `utf-8`.\n\n##### charsetSentinel\n\nWhether to let the value of the `utf8` parameter take precedence as the charset\nselector. It requires the form to contain a parameter named `utf8` with a value\nof `✓`. Defaults to `false`.\n\n##### interpretNumericEntities\n\nWhether to decode numeric entities such as `\u0026#9786;` when parsing an iso-8859-1\nform. Defaults to `false`.\n\n\n#### depth\n\nThe `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.\n\n## Errors\n\nThe middlewares provided by this module create errors using the\n[`http-errors` module](https://www.npmjs.com/package/http-errors). The errors\nwill typically have a `status`/`statusCode` property that contains the suggested\nHTTP response code, an `expose` property to determine if the `message` property\nshould be displayed to the client, a `type` property to determine the type of\nerror without matching against the `message`, and a `body` property containing\nthe read body, if available.\n\nThe following are the common errors created, though any error can come through\nfor various reasons.\n\n### content encoding unsupported\n\nThis error will occur when the request had a `Content-Encoding` header that\ncontained an encoding but the \"inflation\" option was set to `false`. The\n`status` property is set to `415`, the `type` property is set to\n`'encoding.unsupported'`, and the `charset` property will be set to the\nencoding that is unsupported.\n\n### entity parse failed\n\nThis error will occur when the request contained an entity that could not be\nparsed by the middleware. The `status` property is set to `400`, the `type`\nproperty is set to `'entity.parse.failed'`, and the `body` property is set to\nthe entity value that failed parsing.\n\n### entity verify failed\n\nThis error will occur when the request contained an entity that could not be\nfailed verification by the defined `verify` option. The `status` property is\nset to `403`, the `type` property is set to `'entity.verify.failed'`, and the\n`body` property is set to the entity value that failed verification.\n\n### request aborted\n\nThis error will occur when the request is aborted by the client before reading\nthe body has finished. The `received` property will be set to the number of\nbytes received before the request was aborted and the `expected` property is\nset to the number of expected bytes. The `status` property is set to `400`\nand `type` property is set to `'request.aborted'`.\n\n### request entity too large\n\nThis error will occur when the request body's size is larger than the \"limit\"\noption. The `limit` property will be set to the byte limit and the `length`\nproperty will be set to the request body's length. The `status` property is\nset to `413` and the `type` property is set to `'entity.too.large'`.\n\n### request size did not match content length\n\nThis error will occur when the request's length did not match the length from\nthe `Content-Length` header. This typically occurs when the request is malformed,\ntypically when the `Content-Length` header was calculated based on characters\ninstead of bytes. The `status` property is set to `400` and the `type` property\nis set to `'request.size.invalid'`.\n\n### stream encoding should not be set\n\nThis error will occur when something called the `req.setEncoding` method prior\nto this middleware. This module operates directly on bytes only and you cannot\ncall `req.setEncoding` when using this module. The `status` property is set to\n`500` and the `type` property is set to `'stream.encoding.set'`.\n\n### stream is not readable\n\nThis error will occur when the request is no longer readable when this middleware\nattempts to read it. This typically means something other than a middleware from\nthis module read the request body already and the middleware was also configured to\nread the same request. The `status` property is set to `500` and the `type`\nproperty is set to `'stream.not.readable'`.\n\n### too many parameters\n\nThis error will occur when the content of the request exceeds the configured\n`parameterLimit` for the `urlencoded` parser. The `status` property is set to\n`413` and the `type` property is set to `'parameters.too.many'`.\n\n### unsupported charset \"BOGUS\"\n\nThis error will occur when the request had a charset parameter in the\n`Content-Type` header, but the `iconv-lite` module does not support it OR the\nparser does not support it. The charset is contained in the message as well\nas in the `charset` property. The `status` property is set to `415`, the\n`type` property is set to `'charset.unsupported'`, and the `charset` property\nis set to the charset that is unsupported.\n\n### unsupported content encoding \"bogus\"\n\nThis error will occur when the request had a `Content-Encoding` header that\ncontained an unsupported encoding. The encoding is contained in the message\nas well as in the `encoding` property. The `status` property is set to `415`,\nthe `type` property is set to `'encoding.unsupported'`, and the `encoding`\nproperty is set to the encoding that is unsupported.\n\n### The input exceeded the depth\n\nThis 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. When the `depth` option is set to `32` (default value), the error will not be thrown.\n\n## Examples\n\n### Express/Connect top-level generic\n\nThis example demonstrates adding a generic JSON and URL-encoded parser as a\ntop-level middleware, which will parse the bodies of all incoming requests.\nThis is the simplest setup.\n\n```js\nconst express = require('express')\nconst bodyParser = require('body-parser')\n\nconst app = express()\n\n// parse application/x-www-form-urlencoded\napp.use(bodyParser.urlencoded())\n\n// parse application/json\napp.use(bodyParser.json())\n\napp.use(function (req, res) {\n  res.setHeader('Content-Type', 'text/plain')\n  res.write('you posted:\\n')\n  res.end(String(JSON.stringify(req.body, null, 2)))\n})\n```\n\n### Express route-specific\n\nThis example demonstrates adding body parsers specifically to the routes that\nneed them. In general, this is the most recommended way to use body-parser with\nExpress.\n\n```js\nconst express = require('express')\nconst bodyParser = require('body-parser')\n\nconst app = express()\n\n// create application/json parser\nconst jsonParser = bodyParser.json()\n\n// create application/x-www-form-urlencoded parser\nconst urlencodedParser = bodyParser.urlencoded()\n\n// POST /login gets urlencoded bodies\napp.post('/login', urlencodedParser, function (req, res) {\n  if (!req.body || !req.body.username) res.sendStatus(400)\n  res.send('welcome, ' + req.body.username)\n})\n\n// POST /api/users gets JSON bodies\napp.post('/api/users', jsonParser, function (req, res) {\n  if (!req.body) res.sendStatus(400)\n  // create user in req.body\n})\n```\n\n### Change accepted type for parsers\n\nAll the parsers accept a `type` option which allows you to change the\n`Content-Type` that the middleware will parse.\n\n```js\nconst express = require('express')\nconst bodyParser = require('body-parser')\n\nconst app = express()\n\n// parse various different custom JSON types as JSON\napp.use(bodyParser.json({ type: 'application/*+json' }))\n\n// parse some custom thing into a Buffer\napp.use(bodyParser.raw({ type: 'application/vnd.custom-type' }))\n\n// parse an HTML body into a string\napp.use(bodyParser.text({ type: 'text/html' }))\n```\n\n## License\n\n[MIT](LICENSE)\n\n[ci-image]: https://badgen.net/github/checks/expressjs/body-parser/master?label=ci\n[ci-url]: https://github.com/expressjs/body-parser/actions/workflows/ci.yml\n[coveralls-image]: https://badgen.net/coveralls/c/github/expressjs/body-parser/master\n[coveralls-url]: https://coveralls.io/r/expressjs/body-parser?branch=master\n[node-version-image]: https://badgen.net/npm/node/body-parser\n[node-version-url]: https://nodejs.org/en/download\n[npm-downloads-image]: https://badgen.net/npm/dm/body-parser\n[npm-url]: https://npmjs.org/package/body-parser\n[npm-version-image]: https://badgen.net/npm/v/body-parser\n[ossf-scorecard-badge]: https://api.scorecard.dev/projects/github.com/expressjs/body-parser/badge\n[ossf-scorecard-visualizer]: https://ossf.github.io/scorecard-visualizer/#/projects/github.com/expressjs/body-parser","funding_links":["https://opencollective.com/express"],"categories":["express","JavaScript","Uncategorized","NodeJS Interesting Module :seedling: :seedling: :seedling:","javascript","nodejs","中间件","Middleware"],"sub_categories":["Uncategorized"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fexpressjs%2Fbody-parser","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fexpressjs%2Fbody-parser","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fexpressjs%2Fbody-parser/lists"}