source: frontend/node_modules/body-parser/README.md

Last change on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 12 days ago

Fix frontend appearance

  • Property mode set to 100644
File size: 18.7 KB
RevLine 
[9af201e]1# body-parser
2
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, available
12under the `req.body` property.
13
14**Note** As `req.body`'s shape is based on user-controlled input, all
15properties and values in this object are untrusted and should be validated
16before trusting. For example, `req.body.foo.toString()` may fail in multiple
17ways, 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 typically
23large nature. For multipart bodies, you may be interested in the following
24modules:
25
26 * [busboy](https://www.npmjs.org/package/busboy#readme) and
27 [connect-busboy](https://www.npmjs.org/package/connect-busboy#readme)
28 * [multiparty](https://www.npmjs.org/package/multiparty#readme) and
29 [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## Installation
46
47```sh
48$ npm install body-parser
49```
50
51## API
52
53```js
54var bodyParser = require('body-parser')
55```
56
57The `bodyParser` object exposes various factories to create middlewares. All
58middlewares will populate the `req.body` property with the parsed body when
59the `Content-Type` request header matches the `type` option, or an empty
60object (`{}`) 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 the
64[errors section](#errors).
65
66### bodyParser.json([options])
67
68Returns middleware that only parses `json` and only looks at requests where
69the `Content-Type` header matches the `type` option. This parser accepts any
70Unicode encoding of the body and supports automatic inflation of `gzip` and
71`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#### Options
77
78The `json` function takes an optional `options` object that may contain any of
79the following keys:
80
81##### inflate
82
83When set to `true`, then deflated (compressed) bodies will be inflated; when
84`false`, deflated bodies are rejected. Defaults to `true`.
85
86##### limit
87
88Controls the maximum request body size. If this is a number, then the value
89specifies the number of bytes; if it is a string, the value is passed to the
90[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults
91to `'100kb'`.
92
93##### reviver
94
95The `reviver` option is passed directly to `JSON.parse` as the second
96argument. You can find more information on this argument
97[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##### strict
100
101When set to `true`, will only accept arrays and objects; when `false` will
102accept anything `JSON.parse` accepts. Defaults to `true`.
103
104##### type
105
106The `type` option is used to determine what media type the middleware will
107parse. This option can be a string, array of strings, or a function. If not a
108function, `type` option is passed directly to the
109[type-is](https://www.npmjs.org/package/type-is#readme) library and this can
110be an extension name (like `json`), a mime type (like `application/json`), or
111a 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 truthy
113value. Defaults to `application/json`.
114
115##### verify
116
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 the
119encoding 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 at
124requests where the `Content-Type` header matches the `type` option. This
125parser 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` object
129of the body.
130
131#### Options
132
133The `raw` function takes an optional `options` object that may contain any of
134the following keys:
135
136##### inflate
137
138When set to `true`, then deflated (compressed) bodies will be inflated; when
139`false`, deflated bodies are rejected. Defaults to `true`.
140
141##### limit
142
143Controls the maximum request body size. If this is a number, then the value
144specifies the number of bytes; if it is a string, the value is passed to the
145[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults
146to `'100kb'`.
147
148##### type
149
150The `type` option is used to determine what media type the middleware will
151parse. This option can be a string, array of strings, or a function.
152If not a function, `type` option is passed directly to the
153[type-is](https://www.npmjs.org/package/type-is#readme) library and this
154can be an extension name (like `bin`), a mime type (like
155`application/octet-stream`), or a mime type with a wildcard (like `*/*` or
156`application/*`). If a function, the `type` option is called as `fn(req)`
157and the request is parsed if it returns a truthy value. Defaults to
158`application/octet-stream`.
159
160##### verify
161
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 the
164encoding 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 at
169requests where the `Content-Type` header matches the `type` option. This
170parser 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 the
174body.
175
176#### Options
177
178The `text` function takes an optional `options` object that may contain any of
179the following keys:
180
181##### defaultCharset
182
183Specify the default character set for the text content if the charset is not
184specified in the `Content-Type` header of the request. Defaults to `utf-8`.
185
186##### inflate
187
188When set to `true`, then deflated (compressed) bodies will be inflated; when
189`false`, deflated bodies are rejected. Defaults to `true`.
190
191##### limit
192
193Controls the maximum request body size. If this is a number, then the value
194specifies the number of bytes; if it is a string, the value is passed to the
195[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults
196to `'100kb'`.
197
198##### type
199
200The `type` option is used to determine what media type the middleware will
201parse. This option can be a string, array of strings, or a function. If not
202a function, `type` option is passed directly to the
203[type-is](https://www.npmjs.org/package/type-is#readme) library and this can
204be an extension name (like `txt`), a mime type (like `text/plain`), or a mime
205type 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 a
207truthy value. Defaults to `text/plain`.
208
209##### verify
210
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 the
213encoding 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 at
218requests where the `Content-Type` header matches the `type` option. This
219parser accepts only UTF-8 encoding of the body and supports automatic
220inflation 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 contain
224key-value pairs, where the value can be a string or array (when `extended` is
225`false`), or any type (when `extended` is `true`).
226
227#### Options
228
229The `urlencoded` function takes an optional `options` object that may contain
230any of the following keys:
231
232##### extended
233
234The `extended` option allows to choose between parsing the URL-encoded data
235with the `querystring` library (when `false`) or the `qs` library (when
236`true`). The "extended" syntax allows for rich objects and arrays to be
237encoded into the URL-encoded format, allowing for a JSON-like experience
238with URL-encoded. For more information, please
239[see the qs library](https://www.npmjs.org/package/qs#readme).
240
241Defaults to `true`, but using the default has been deprecated. Please
242research into the difference between `qs` and `querystring` and choose the
243appropriate setting.
244
245##### inflate
246
247When set to `true`, then deflated (compressed) bodies will be inflated; when
248`false`, deflated bodies are rejected. Defaults to `true`.
249
250##### limit
251
252Controls the maximum request body size. If this is a number, then the value
253specifies the number of bytes; if it is a string, the value is passed to the
254[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults
255to `'100kb'`.
256
257##### parameterLimit
258
259The `parameterLimit` option controls the maximum number of parameters that
260are allowed in the URL-encoded data. If a request contains more parameters
261than this value, a 413 will be returned to the client. Defaults to `1000`.
262
263##### type
264
265The `type` option is used to determine what media type the middleware will
266parse. This option can be a string, array of strings, or a function. If not
267a function, `type` option is passed directly to the
268[type-is](https://www.npmjs.org/package/type-is#readme) library and this can
269be an extension name (like `urlencoded`), a mime type (like
270`application/x-www-form-urlencoded`), or a mime type with a wildcard (like
271`*/x-www-form-urlencoded`). If a function, the `type` option is called as
272`fn(req)` and the request is parsed if it returns a truthy value. Defaults
273to `application/x-www-form-urlencoded`.
274
275##### verify
276
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 the
279encoding of the request. The parsing can be aborted by throwing an error.
280
281#### depth
282
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## Errors
286
287The middlewares provided by this module create errors using the
288[`http-errors` module](https://www.npmjs.com/package/http-errors). The errors
289will typically have a `status`/`statusCode` property that contains the suggested
290HTTP response code, an `expose` property to determine if the `message` property
291should be displayed to the client, a `type` property to determine the type of
292error without matching against the `message`, and a `body` property containing
293the read body, if available.
294
295The following are the common errors created, though any error can come through
296for various reasons.
297
298### content encoding unsupported
299
300This error will occur when the request had a `Content-Encoding` header that
301contained an encoding but the "inflation" option was set to `false`. The
302`status` property is set to `415`, the `type` property is set to
303`'encoding.unsupported'`, and the `charset` property will be set to the
304encoding that is unsupported.
305
306### entity parse failed
307
308This error will occur when the request contained an entity that could not be
309parsed 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 to
311the entity value that failed parsing.
312
313### entity verify failed
314
315This error will occur when the request contained an entity that could not be
316failed verification by the defined `verify` option. The `status` property is
317set to `403`, the `type` property is set to `'entity.verify.failed'`, and the
318`body` property is set to the entity value that failed verification.
319
320### request aborted
321
322This error will occur when the request is aborted by the client before reading
323the body has finished. The `received` property will be set to the number of
324bytes received before the request was aborted and the `expected` property is
325set 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 large
329
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 is
333set to `413` and the `type` property is set to `'entity.too.large'`.
334
335### request size did not match content length
336
337This error will occur when the request's length did not match the length from
338the `Content-Length` header. This typically occurs when the request is malformed,
339typically when the `Content-Length` header was calculated based on characters
340instead of bytes. The `status` property is set to `400` and the `type` property
341is set to `'request.size.invalid'`.
342
343### stream encoding should not be set
344
345This error will occur when something called the `req.setEncoding` method prior
346to this middleware. This module operates directly on bytes only and you cannot
347call `req.setEncoding` when using this module. The `status` property is set to
348`500` and the `type` property is set to `'stream.encoding.set'`.
349
350### stream is not readable
351
352This error will occur when the request is no longer readable when this middleware
353attempts to read it. This typically means something other than a middleware from
354this module read the request body already and the middleware was also configured to
355read the same request. The `status` property is set to `500` and the `type`
356property is set to `'stream.not.readable'`.
357
358### too many parameters
359
360This error will occur when the content of the request exceeds the configured
361`parameterLimit` for the `urlencoded` parser. The `status` property is set to
362`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 the
367`Content-Type` header, but the `iconv-lite` module does not support it OR the
368parser does not support it. The charset is contained in the message as well
369as in the `charset` property. The `status` property is set to `415`, the
370`type` property is set to `'charset.unsupported'`, and the `charset` property
371is 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 that
376contained an unsupported encoding. The encoding is contained in the message
377as 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 depth
382
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## Examples
386
387### Express/Connect top-level generic
388
389This example demonstrates adding a generic JSON and URL-encoded parser as a
390top-level middleware, which will parse the bodies of all incoming requests.
391This is the simplest setup.
392
393```js
394var express = require('express')
395var bodyParser = require('body-parser')
396
397var app = express()
398
399// parse application/x-www-form-urlencoded
400app.use(bodyParser.urlencoded({ extended: false }))
401
402// parse application/json
403app.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-specific
413
414This example demonstrates adding body parsers specifically to the routes that
415need them. In general, this is the most recommended way to use body-parser with
416Express.
417
418```js
419var express = require('express')
420var bodyParser = require('body-parser')
421
422var app = express()
423
424// create application/json parser
425var jsonParser = bodyParser.json()
426
427// create application/x-www-form-urlencoded parser
428var urlencodedParser = bodyParser.urlencoded({ extended: false })
429
430// POST /login gets urlencoded bodies
431app.post('/login', urlencodedParser, function (req, res) {
432 res.send('welcome, ' + req.body.username)
433})
434
435// POST /api/users gets JSON bodies
436app.post('/api/users', jsonParser, function (req, res) {
437 // create user in req.body
438})
439```
440
441### Change accepted type for parsers
442
443All the parsers accept a `type` option which allows you to change the
444`Content-Type` that the middleware will parse.
445
446```js
447var express = require('express')
448var bodyParser = require('body-parser')
449
450var app = express()
451
452// parse various different custom JSON types as JSON
453app.use(bodyParser.json({ type: 'application/*+json' }))
454
455// parse some custom thing into a Buffer
456app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }))
457
458// parse an HTML body into a string
459app.use(bodyParser.text({ type: 'text/html' }))
460```
461
462## License
463
464[MIT](LICENSE)
465
466[ci-image]: https://badgen.net/github/checks/expressjs/body-parser/master?label=ci
467[ci-url]: https://github.com/expressjs/body-parser/actions/workflows/ci.yml
468[coveralls-image]: https://badgen.net/coveralls/c/github/expressjs/body-parser/master
469[coveralls-url]: https://coveralls.io/r/expressjs/body-parser?branch=master
470[node-version-image]: https://badgen.net/npm/node/body-parser
471[node-version-url]: https://nodejs.org/en/download
472[npm-downloads-image]: https://badgen.net/npm/dm/body-parser
473[npm-url]: https://npmjs.org/package/body-parser
474[npm-version-image]: https://badgen.net/npm/v/body-parser
475[ossf-scorecard-badge]: https://api.scorecard.dev/projects/github.com/expressjs/body-parser/badge
476[ossf-scorecard-visualizer]: https://ossf.github.io/scorecard-visualizer/#/projects/github.com/expressjs/body-parser
Note: See TracBrowser for help on using the repository browser.