CoolFace
Apppublic

opusdev/vector-similarity-api

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes
README.md476 linesDownload Raw Back to body-parser
1# body-parser2 3[![NPM Version][npm-version-image]][npm-url]4[![NPM Downloads][npm-downloads-image]][npm-url]5[![Build Status][ci-image]][ci-url]6[![Test Coverage][coveralls-image]][coveralls-url]7[![OpenSSF Scorecard Badge][ossf-scorecard-badge]][ossf-scorecard-visualizer]8 9Node.js body parsing middleware.10 11Parse incoming request bodies in a middleware before your handlers, available12under the `req.body` property.13 14**Note** As `req.body`'s shape is based on user-controlled input, all15properties and values in this object are untrusted and should be validated16before trusting. For example, `req.body.foo.toString()` may fail in multiple17ways, for example the `foo` property may not be there or may not be a string,18and `toString` may not be a function and instead a string or other user input.19 20[Learn about the anatomy of an HTTP transaction in Node.js](https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/).21 22_This does not handle multipart bodies_, due to their complex and typically23large nature. For multipart bodies, you may be interested in the following24modules:25 26  * [busboy](https://www.npmjs.org/package/busboy#readme) and27    [connect-busboy](https://www.npmjs.org/package/connect-busboy#readme)28  * [multiparty](https://www.npmjs.org/package/multiparty#readme) and29    [connect-multiparty](https://www.npmjs.org/package/connect-multiparty#readme)30  * [formidable](https://www.npmjs.org/package/formidable#readme)31  * [multer](https://www.npmjs.org/package/multer#readme)32 33This module provides the following parsers:34 35  * [JSON body parser](#bodyparserjsonoptions)36  * [Raw body parser](#bodyparserrawoptions)37  * [Text body parser](#bodyparsertextoptions)38  * [URL-encoded form body parser](#bodyparserurlencodedoptions)39 40Other body parsers you might be interested in:41 42- [body](https://www.npmjs.org/package/body#readme)43- [co-body](https://www.npmjs.org/package/co-body#readme)44 45## Installation46 47```sh48$ npm install body-parser49```50 51## API52 53```js54var bodyParser = require('body-parser')55```56 57The `bodyParser` object exposes various factories to create middlewares. All58middlewares will populate the `req.body` property with the parsed body when59the `Content-Type` request header matches the `type` option, or an empty60object (`{}`) if there was no body to parse, the `Content-Type` was not matched,61or an error occurred.62 63The various errors returned by this module are described in the64[errors section](#errors).65 66### bodyParser.json([options])67 68Returns middleware that only parses `json` and only looks at requests where69the `Content-Type` header matches the `type` option. This parser accepts any70Unicode encoding of the body and supports automatic inflation of `gzip` and71`deflate` encodings.72 73A new `body` object containing the parsed data is populated on the `request`74object after the middleware (i.e. `req.body`).75 76#### Options77 78The `json` function takes an optional `options` object that may contain any of79the following keys:80 81##### inflate82 83When set to `true`, then deflated (compressed) bodies will be inflated; when84`false`, deflated bodies are rejected. Defaults to `true`.85 86##### limit87 88Controls the maximum request body size. If this is a number, then the value89specifies the number of bytes; if it is a string, the value is passed to the90[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults91to `'100kb'`.92 93##### reviver94 95The `reviver` option is passed directly to `JSON.parse` as the second96argument. You can find more information on this argument97[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).98 99##### strict100 101When set to `true`, will only accept arrays and objects; when `false` will102accept anything `JSON.parse` accepts. Defaults to `true`.103 104##### type105 106The `type` option is used to determine what media type the middleware will107parse. This option can be a string, array of strings, or a function. If not a108function, `type` option is passed directly to the109[type-is](https://www.npmjs.org/package/type-is#readme) library and this can110be an extension name (like `json`), a mime type (like `application/json`), or111a mime type with a wildcard (like `*/*` or `*/json`). If a function, the `type`112option is called as `fn(req)` and the request is parsed if it returns a truthy113value. Defaults to `application/json`.114 115##### verify116 117The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`,118where `buf` is a `Buffer` of the raw request body and `encoding` is the119encoding of the request. The parsing can be aborted by throwing an error.120 121### bodyParser.raw([options])122 123Returns middleware that parses all bodies as a `Buffer` and only looks at124requests where the `Content-Type` header matches the `type` option. This125parser supports automatic inflation of `gzip` and `deflate` encodings.126 127A new `body` object containing the parsed data is populated on the `request`128object after the middleware (i.e. `req.body`). This will be a `Buffer` object129of the body.130 131#### Options132 133The `raw` function takes an optional `options` object that may contain any of134the following keys:135 136##### inflate137 138When set to `true`, then deflated (compressed) bodies will be inflated; when139`false`, deflated bodies are rejected. Defaults to `true`.140 141##### limit142 143Controls the maximum request body size. If this is a number, then the value144specifies the number of bytes; if it is a string, the value is passed to the145[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults146to `'100kb'`.147 148##### type149 150The `type` option is used to determine what media type the middleware will151parse. This option can be a string, array of strings, or a function.152If not a function, `type` option is passed directly to the153[type-is](https://www.npmjs.org/package/type-is#readme) library and this154can be an extension name (like `bin`), a mime type (like155`application/octet-stream`), or a mime type with a wildcard (like `*/*` or156`application/*`). If a function, the `type` option is called as `fn(req)`157and the request is parsed if it returns a truthy value. Defaults to158`application/octet-stream`.159 160##### verify161 162The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`,163where `buf` is a `Buffer` of the raw request body and `encoding` is the164encoding of the request. The parsing can be aborted by throwing an error.165 166### bodyParser.text([options])167 168Returns middleware that parses all bodies as a string and only looks at169requests where the `Content-Type` header matches the `type` option. This170parser supports automatic inflation of `gzip` and `deflate` encodings.171 172A new `body` string containing the parsed data is populated on the `request`173object after the middleware (i.e. `req.body`). This will be a string of the174body.175 176#### Options177 178The `text` function takes an optional `options` object that may contain any of179the following keys:180 181##### defaultCharset182 183Specify the default character set for the text content if the charset is not184specified in the `Content-Type` header of the request. Defaults to `utf-8`.185 186##### inflate187 188When set to `true`, then deflated (compressed) bodies will be inflated; when189`false`, deflated bodies are rejected. Defaults to `true`.190 191##### limit192 193Controls the maximum request body size. If this is a number, then the value194specifies the number of bytes; if it is a string, the value is passed to the195[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults196to `'100kb'`.197 198##### type199 200The `type` option is used to determine what media type the middleware will201parse. This option can be a string, array of strings, or a function. If not202a function, `type` option is passed directly to the203[type-is](https://www.npmjs.org/package/type-is#readme) library and this can204be an extension name (like `txt`), a mime type (like `text/plain`), or a mime205type with a wildcard (like `*/*` or `text/*`). If a function, the `type`206option is called as `fn(req)` and the request is parsed if it returns a207truthy value. Defaults to `text/plain`.208 209##### verify210 211The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`,212where `buf` is a `Buffer` of the raw request body and `encoding` is the213encoding of the request. The parsing can be aborted by throwing an error.214 215### bodyParser.urlencoded([options])216 217Returns middleware that only parses `urlencoded` bodies and only looks at218requests where the `Content-Type` header matches the `type` option. This219parser accepts only UTF-8 encoding of the body and supports automatic220inflation of `gzip` and `deflate` encodings.221 222A new `body` object containing the parsed data is populated on the `request`223object after the middleware (i.e. `req.body`). This object will contain224key-value pairs, where the value can be a string or array (when `extended` is225`false`), or any type (when `extended` is `true`).226 227#### Options228 229The `urlencoded` function takes an optional `options` object that may contain230any of the following keys:231 232##### extended233 234The `extended` option allows to choose between parsing the URL-encoded data235with the `querystring` library (when `false`) or the `qs` library (when236`true`). The "extended" syntax allows for rich objects and arrays to be237encoded into the URL-encoded format, allowing for a JSON-like experience238with URL-encoded. For more information, please239[see the qs library](https://www.npmjs.org/package/qs#readme).240 241Defaults to `true`, but using the default has been deprecated. Please242research into the difference between `qs` and `querystring` and choose the243appropriate setting.244 245##### inflate246 247When set to `true`, then deflated (compressed) bodies will be inflated; when248`false`, deflated bodies are rejected. Defaults to `true`.249 250##### limit251 252Controls the maximum request body size. If this is a number, then the value253specifies the number of bytes; if it is a string, the value is passed to the254[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults255to `'100kb'`.256 257##### parameterLimit258 259The `parameterLimit` option controls the maximum number of parameters that260are allowed in the URL-encoded data. If a request contains more parameters261than this value, a 413 will be returned to the client. Defaults to `1000`.262 263##### type264 265The `type` option is used to determine what media type the middleware will266parse. This option can be a string, array of strings, or a function. If not267a function, `type` option is passed directly to the268[type-is](https://www.npmjs.org/package/type-is#readme) library and this can269be an extension name (like `urlencoded`), a mime type (like270`application/x-www-form-urlencoded`), or a mime type with a wildcard (like271`*/x-www-form-urlencoded`). If a function, the `type` option is called as272`fn(req)` and the request is parsed if it returns a truthy value. Defaults273to `application/x-www-form-urlencoded`.274 275##### verify276 277The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`,278where `buf` is a `Buffer` of the raw request body and `encoding` is the279encoding of the request. The parsing can be aborted by throwing an error.280 281#### depth282 283The `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.284 285## Errors286 287The middlewares provided by this module create errors using the288[`http-errors` module](https://www.npmjs.com/package/http-errors). The errors289will typically have a `status`/`statusCode` property that contains the suggested290HTTP response code, an `expose` property to determine if the `message` property291should be displayed to the client, a `type` property to determine the type of292error without matching against the `message`, and a `body` property containing293the read body, if available.294 295The following are the common errors created, though any error can come through296for various reasons.297 298### content encoding unsupported299 300This error will occur when the request had a `Content-Encoding` header that301contained an encoding but the "inflation" option was set to `false`. The302`status` property is set to `415`, the `type` property is set to303`'encoding.unsupported'`, and the `charset` property will be set to the304encoding that is unsupported.305 306### entity parse failed307 308This error will occur when the request contained an entity that could not be309parsed by the middleware. The `status` property is set to `400`, the `type`310property is set to `'entity.parse.failed'`, and the `body` property is set to311the entity value that failed parsing.312 313### entity verify failed314 315This error will occur when the request contained an entity that could not be316failed verification by the defined `verify` option. The `status` property is317set to `403`, the `type` property is set to `'entity.verify.failed'`, and the318`body` property is set to the entity value that failed verification.319 320### request aborted321 322This error will occur when the request is aborted by the client before reading323the body has finished. The `received` property will be set to the number of324bytes received before the request was aborted and the `expected` property is325set to the number of expected bytes. The `status` property is set to `400`326and `type` property is set to `'request.aborted'`.327 328### request entity too large329 330This error will occur when the request body's size is larger than the "limit"331option. The `limit` property will be set to the byte limit and the `length`332property will be set to the request body's length. The `status` property is333set to `413` and the `type` property is set to `'entity.too.large'`.334 335### request size did not match content length336 337This error will occur when the request's length did not match the length from338the `Content-Length` header. This typically occurs when the request is malformed,339typically when the `Content-Length` header was calculated based on characters340instead of bytes. The `status` property is set to `400` and the `type` property341is set to `'request.size.invalid'`.342 343### stream encoding should not be set344 345This error will occur when something called the `req.setEncoding` method prior346to this middleware. This module operates directly on bytes only and you cannot347call `req.setEncoding` when using this module. The `status` property is set to348`500` and the `type` property is set to `'stream.encoding.set'`.349 350### stream is not readable351 352This error will occur when the request is no longer readable when this middleware353attempts to read it. This typically means something other than a middleware from354this module read the request body already and the middleware was also configured to355read the same request. The `status` property is set to `500` and the `type`356property is set to `'stream.not.readable'`.357 358### too many parameters359 360This error will occur when the content of the request exceeds the configured361`parameterLimit` for the `urlencoded` parser. The `status` property is set to362`413` and the `type` property is set to `'parameters.too.many'`.363 364### unsupported charset "BOGUS"365 366This error will occur when the request had a charset parameter in the367`Content-Type` header, but the `iconv-lite` module does not support it OR the368parser does not support it. The charset is contained in the message as well369as in the `charset` property. The `status` property is set to `415`, the370`type` property is set to `'charset.unsupported'`, and the `charset` property371is set to the charset that is unsupported.372 373### unsupported content encoding "bogus"374 375This error will occur when the request had a `Content-Encoding` header that376contained an unsupported encoding. The encoding is contained in the message377as well as in the `encoding` property. The `status` property is set to `415`,378the `type` property is set to `'encoding.unsupported'`, and the `encoding`379property is set to the encoding that is unsupported.380 381### The input exceeded the depth382 383This 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.384 385## Examples386 387### Express/Connect top-level generic388 389This example demonstrates adding a generic JSON and URL-encoded parser as a390top-level middleware, which will parse the bodies of all incoming requests.391This is the simplest setup.392 393```js394var express = require('express')395var bodyParser = require('body-parser')396 397var app = express()398 399// parse application/x-www-form-urlencoded400app.use(bodyParser.urlencoded({ extended: false }))401 402// parse application/json403app.use(bodyParser.json())404 405app.use(function (req, res) {406  res.setHeader('Content-Type', 'text/plain')407  res.write('you posted:\n')408  res.end(JSON.stringify(req.body, null, 2))409})410```411 412### Express route-specific413 414This example demonstrates adding body parsers specifically to the routes that415need them. In general, this is the most recommended way to use body-parser with416Express.417 418```js419var express = require('express')420var bodyParser = require('body-parser')421 422var app = express()423 424// create application/json parser425var jsonParser = bodyParser.json()426 427// create application/x-www-form-urlencoded parser428var urlencodedParser = bodyParser.urlencoded({ extended: false })429 430// POST /login gets urlencoded bodies431app.post('/login', urlencodedParser, function (req, res) {432  res.send('welcome, ' + req.body.username)433})434 435// POST /api/users gets JSON bodies436app.post('/api/users', jsonParser, function (req, res) {437  // create user in req.body438})439```440 441### Change accepted type for parsers442 443All the parsers accept a `type` option which allows you to change the444`Content-Type` that the middleware will parse.445 446```js447var express = require('express')448var bodyParser = require('body-parser')449 450var app = express()451 452// parse various different custom JSON types as JSON453app.use(bodyParser.json({ type: 'application/*+json' }))454 455// parse some custom thing into a Buffer456app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }))457 458// parse an HTML body into a string459app.use(bodyParser.text({ type: 'text/html' }))460```461 462## License463 464[MIT](LICENSE)465 466[ci-image]: https://badgen.net/github/checks/expressjs/body-parser/master?label=ci467[ci-url]: https://github.com/expressjs/body-parser/actions/workflows/ci.yml468[coveralls-image]: https://badgen.net/coveralls/c/github/expressjs/body-parser/master469[coveralls-url]: https://coveralls.io/r/expressjs/body-parser?branch=master470[node-version-image]: https://badgen.net/npm/node/body-parser471[node-version-url]: https://nodejs.org/en/download472[npm-downloads-image]: https://badgen.net/npm/dm/body-parser473[npm-url]: https://npmjs.org/package/body-parser474[npm-version-image]: https://badgen.net/npm/v/body-parser475[ossf-scorecard-badge]: https://api.scorecard.dev/projects/github.com/expressjs/body-parser/badge476[ossf-scorecard-visualizer]: https://ossf.github.io/scorecard-visualizer/#/projects/github.com/expressjs/body-parser