Neuste Version
This commit is contained in:
+23
@@ -0,0 +1,23 @@
|
||||
(The MIT License)
|
||||
|
||||
Copyright (c) 2014 Jonathan Ong <me@jongleberry.com>
|
||||
Copyright (c) 2014-2015 Douglas Christopher Wilson <doug@somethingdoug.com>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
'Software'), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
|
||||
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
||||
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
+509
@@ -0,0 +1,509 @@
|
||||
# body-parser
|
||||
|
||||
[![NPM Version][npm-version-image]][npm-url]
|
||||
[![NPM Downloads][npm-downloads-image]][npm-url]
|
||||
[![Build Status][ci-image]][ci-url]
|
||||
[![Test Coverage][coveralls-image]][coveralls-url]
|
||||
[![OpenSSF Scorecard Badge][ossf-scorecard-badge]][ossf-scorecard-visualizer]
|
||||
|
||||
Node.js body parsing middleware.
|
||||
|
||||
Parse incoming request bodies in a middleware before your handlers, available
|
||||
under the `req.body` property.
|
||||
|
||||
**Note** As `req.body`'s shape is based on user-controlled input, all
|
||||
properties and values in this object are untrusted and should be validated
|
||||
before trusting. 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](https://nodejs.org/en/learn/http/anatomy-of-an-http-transaction).
|
||||
|
||||
_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:
|
||||
|
||||
* [busboy](https://www.npmjs.com/package/busboy#readme) and
|
||||
[connect-busboy](https://www.npmjs.com/package/connect-busboy#readme)
|
||||
* [multiparty](https://www.npmjs.com/package/multiparty#readme) and
|
||||
[connect-multiparty](https://www.npmjs.com/package/connect-multiparty#readme)
|
||||
* [formidable](https://www.npmjs.com/package/formidable#readme)
|
||||
* [multer](https://www.npmjs.com/package/multer#readme)
|
||||
|
||||
This module provides the following parsers:
|
||||
|
||||
* [JSON body parser](#bodyparserjsonoptions)
|
||||
* [Raw body parser](#bodyparserrawoptions)
|
||||
* [Text body parser](#bodyparsertextoptions)
|
||||
* [URL-encoded form body parser](#bodyparserurlencodedoptions)
|
||||
|
||||
Other body parsers you might be interested in:
|
||||
|
||||
- [body](https://www.npmjs.com/package/body#readme)
|
||||
- [co-body](https://www.npmjs.com/package/co-body#readme)
|
||||
|
||||
## Installation
|
||||
|
||||
```sh
|
||||
$ npm install body-parser
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
```js
|
||||
// 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')
|
||||
```
|
||||
|
||||
The `bodyParser` object exposes various factories to create middlewares. All
|
||||
middlewares will populate the `req.body` property with the parsed body when
|
||||
the `Content-Type` request header matches the `type` option.
|
||||
|
||||
The various errors returned by this module are described in the
|
||||
[errors section](#errors).
|
||||
|
||||
### 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 and supports automatic inflation of `gzip`,
|
||||
`br` (brotli) and `deflate` encodings.
|
||||
|
||||
A new `body` object containing the parsed data is populated on the `request`
|
||||
object after the middleware (i.e. `req.body`).
|
||||
|
||||
#### Options
|
||||
|
||||
The `json` function takes an optional `options` object that may contain any of
|
||||
the following keys:
|
||||
|
||||
##### defaultCharset
|
||||
|
||||
Specify the default character set for the json content if the charset is not
|
||||
specified in the `Content-Type` header of the request. Defaults to `utf-8`.
|
||||
|
||||
##### inflate
|
||||
|
||||
When set to `true`, then deflated (compressed) bodies will be inflated; when
|
||||
`false`, deflated bodies are rejected. Defaults to `true`.
|
||||
|
||||
##### limit
|
||||
|
||||
Controls the maximum request body size. If this is a number, then the value
|
||||
specifies the number of bytes; if it is a string, the value is passed to the
|
||||
[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults
|
||||
to `'100kb'`.
|
||||
|
||||
> It’s recommended not to configure a very high limit and to use the default value whenever possible. Allowing larger payloads increases memory usage because of the resources required for decoding and transformations, and it can also lead to longer response times as more data is processed. By ‘very high’, we mean values above the default, for example payloads of 5 MB or more can already start to introduce these risks. With the default limits, these issues do not occur.
|
||||
|
||||
##### reviver
|
||||
|
||||
The `reviver` option 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#the_reviver_parameter).
|
||||
|
||||
##### strict
|
||||
|
||||
When set to `true`, will only accept arrays and objects; when `false` will
|
||||
accept anything `JSON.parse` accepts. Defaults to `true`.
|
||||
|
||||
##### type
|
||||
|
||||
The `type` option is used to determine what media type the middleware will
|
||||
parse. This option can be a string, array of strings, or a function. If not a
|
||||
function, `type` option is passed directly to the
|
||||
[type-is](https://www.npmjs.com/package/type-is#readme) 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`). 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/json`.
|
||||
|
||||
##### verify
|
||||
|
||||
The `verify` option, 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.
|
||||
|
||||
### bodyParser.raw([options])
|
||||
|
||||
Returns middleware that parses all bodies as a `Buffer` and only looks at
|
||||
requests where the `Content-Type` header matches the `type` option. This
|
||||
parser supports automatic inflation of `gzip`, `br` (brotli) and `deflate`
|
||||
encodings.
|
||||
|
||||
A new `body` object containing the parsed data is populated on the `request`
|
||||
object after the middleware (i.e. `req.body`). This will be a `Buffer` object
|
||||
of the body.
|
||||
|
||||
#### Options
|
||||
|
||||
The `raw` function takes an optional `options` object that may contain any of
|
||||
the following keys:
|
||||
|
||||
##### inflate
|
||||
|
||||
When set to `true`, then deflated (compressed) bodies will be inflated; when
|
||||
`false`, deflated bodies are rejected. Defaults to `true`.
|
||||
|
||||
##### limit
|
||||
|
||||
Controls the maximum request body size. If this is a number, then the value
|
||||
specifies the number of bytes; if it is a string, the value is passed to the
|
||||
[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults
|
||||
to `'100kb'`.
|
||||
|
||||
> It’s recommended not to configure a very high limit and to use the default value whenever possible. Allowing larger payloads increases memory usage because of the resources required for decoding and transformations, and it can also lead to longer response times as more data is processed. By ‘very high’, we mean values above the default, for example payloads of 5 MB or more can already start to introduce these risks. With the default limits, these issues do not occur.
|
||||
|
||||
##### type
|
||||
|
||||
The `type` option is used to determine what media type the middleware will
|
||||
parse. This option can be a string, array of strings, or a function.
|
||||
If not a function, `type` option is passed directly to the
|
||||
[type-is](https://www.npmjs.com/package/type-is#readme) 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/*`). 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/octet-stream`.
|
||||
|
||||
##### verify
|
||||
|
||||
The `verify` option, 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.
|
||||
|
||||
### bodyParser.text([options])
|
||||
|
||||
Returns middleware that parses all bodies as a string and only looks at
|
||||
requests where the `Content-Type` header matches the `type` option. This
|
||||
parser supports automatic inflation of `gzip`, `br` (brotli) and `deflate`
|
||||
encodings.
|
||||
|
||||
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.
|
||||
|
||||
#### Options
|
||||
|
||||
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. Defaults to `utf-8`.
|
||||
|
||||
##### inflate
|
||||
|
||||
When set to `true`, then deflated (compressed) bodies will be inflated; when
|
||||
`false`, deflated bodies are rejected. Defaults to `true`.
|
||||
|
||||
##### limit
|
||||
|
||||
Controls the maximum request body size. If this is a number, then the value
|
||||
specifies the number of bytes; if it is a string, the value is passed to the
|
||||
[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults
|
||||
to `'100kb'`.
|
||||
|
||||
> It’s recommended not to configure a very high limit and to use the default value whenever possible. Allowing larger payloads increases memory usage because of the resources required for decoding and transformations, and it can also lead to longer response times as more data is processed. By ‘very high’, we mean values above the default, for example payloads of 5 MB or more can already start to introduce these risks. With the default limits, these issues do not occur.
|
||||
|
||||
##### type
|
||||
|
||||
The `type` option is used to determine what media type the middleware will
|
||||
parse. This option can be a string, array of strings, or a function. If not
|
||||
a function, `type` option is passed directly to the
|
||||
[type-is](https://www.npmjs.com/package/type-is#readme) 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
|
||||
|
||||
The `verify` option, 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.
|
||||
|
||||
### 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 and supports
|
||||
automatic inflation of `gzip`, `br` (brotli) and `deflate` encodings.
|
||||
|
||||
A new `body` object containing the parsed data is populated on the `request`
|
||||
object after the middleware (i.e. `req.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`).
|
||||
|
||||
#### Options
|
||||
|
||||
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](https://www.npmjs.com/package/qs#readme).
|
||||
|
||||
Defaults to `false`.
|
||||
|
||||
##### inflate
|
||||
|
||||
When set to `true`, then deflated (compressed) bodies will be inflated; when
|
||||
`false`, deflated bodies are rejected. Defaults to `true`.
|
||||
|
||||
##### limit
|
||||
|
||||
Controls the maximum request body size. If this is a number, then the value
|
||||
specifies the number of bytes; if it is a string, the value is passed to the
|
||||
[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults
|
||||
to `'100kb'`.
|
||||
|
||||
> It’s recommended not to configure a very high limit and to use the default value whenever possible. Allowing larger payloads increases memory usage because of the resources required for decoding and transformations, and it can also lead to longer response times as more data is processed. By ‘very high’, we mean values above the default, for example payloads of 5 MB or more can already start to introduce these risks. With the default limits, these issues do not occur.
|
||||
|
||||
##### 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
|
||||
|
||||
The `type` option is used to determine what media type the middleware will
|
||||
parse. This option can be a string, array of strings, or a function. If not
|
||||
a function, `type` option is passed directly to the
|
||||
[type-is](https://www.npmjs.com/package/type-is#readme) 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
|
||||
|
||||
The `verify` option, 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.
|
||||
|
||||
##### defaultCharset
|
||||
|
||||
The default charset to parse as, if not specified in content-type. Must be
|
||||
either `utf-8` or `iso-8859-1`. Defaults to `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](https://www.npmjs.com/package/http-errors). 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
|
||||
failed verification 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. When the `depth` option is set to `32` (default value), the error will not be thrown.
|
||||
|
||||
## Examples
|
||||
|
||||
### 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.
|
||||
|
||||
```js
|
||||
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.
|
||||
|
||||
```js
|
||||
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.
|
||||
|
||||
```js
|
||||
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' }))
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
[MIT](LICENSE)
|
||||
|
||||
[ci-image]: https://img.shields.io/github/actions/workflow/status/expressjs/body-parser/ci.yml?branch=master&label=ci
|
||||
[ci-url]: https://github.com/expressjs/body-parser/actions/workflows/ci.yml
|
||||
[coveralls-image]: https://img.shields.io/coverallsCoverage/github/expressjs/body-parser?branch=master
|
||||
[coveralls-url]: https://coveralls.io/r/expressjs/body-parser?branch=master
|
||||
[npm-downloads-image]: https://img.shields.io/npm/dm/body-parser
|
||||
[npm-url]: https://npmjs.com/package/body-parser
|
||||
[npm-version-image]: https://img.shields.io/npm/v/body-parser
|
||||
[ossf-scorecard-badge]: https://api.scorecard.dev/projects/github.com/expressjs/body-parser/badge
|
||||
[ossf-scorecard-visualizer]: https://ossf.github.io/scorecard-visualizer/#/projects/github.com/expressjs/body-parser
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
/*!
|
||||
* body-parser
|
||||
* Copyright(c) 2014-2015 Douglas Christopher Wilson
|
||||
* MIT Licensed
|
||||
*/
|
||||
|
||||
'use strict'
|
||||
|
||||
/**
|
||||
* @typedef {Object} Parsers
|
||||
* @property {Function} json JSON parser
|
||||
* @property {Function} raw Raw parser
|
||||
* @property {Function} text Text parser
|
||||
* @property {Function} urlencoded URL-encoded parser
|
||||
*/
|
||||
|
||||
/**
|
||||
* Module exports.
|
||||
* @type {Function & Parsers}
|
||||
*/
|
||||
exports = module.exports = bodyParser
|
||||
|
||||
/**
|
||||
* JSON parser.
|
||||
* @public
|
||||
*/
|
||||
exports.json = require('./lib/types/json')
|
||||
|
||||
/**
|
||||
* Raw parser.
|
||||
* @public
|
||||
*/
|
||||
exports.raw = require('./lib/types/raw')
|
||||
|
||||
/**
|
||||
* Text parser.
|
||||
* @public
|
||||
*/
|
||||
exports.text = require('./lib/types/text')
|
||||
|
||||
/**
|
||||
* URL-encoded parser.
|
||||
* @public
|
||||
*/
|
||||
exports.urlencoded = require('./lib/types/urlencoded')
|
||||
|
||||
/**
|
||||
* Create a middleware to parse json and urlencoded bodies.
|
||||
*
|
||||
* @deprecated
|
||||
* @public
|
||||
*/
|
||||
function bodyParser () {
|
||||
throw new Error('The bodyParser() generic has been split into individual middleware to use instead.')
|
||||
}
|
||||
+247
@@ -0,0 +1,247 @@
|
||||
/*!
|
||||
* body-parser
|
||||
* Copyright(c) 2014-2015 Douglas Christopher Wilson
|
||||
* MIT Licensed
|
||||
*/
|
||||
|
||||
'use strict'
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
* @private
|
||||
*/
|
||||
|
||||
const createError = require('http-errors')
|
||||
const getBody = require('raw-body')
|
||||
const iconv = require('iconv-lite')
|
||||
const onFinished = require('on-finished')
|
||||
const zlib = require('node:zlib')
|
||||
const hasBody = require('type-is').hasBody
|
||||
const { getCharset } = require('./utils')
|
||||
|
||||
/**
|
||||
* Module exports.
|
||||
*/
|
||||
|
||||
module.exports = read
|
||||
|
||||
/**
|
||||
* Read a request into a buffer and parse.
|
||||
*
|
||||
* @param {Object} req
|
||||
* @param {Object} res
|
||||
* @param {Function} next
|
||||
* @param {Function} parse
|
||||
* @param {Function} debug
|
||||
* @param {Object} options
|
||||
* @private
|
||||
*/
|
||||
function read (req, res, next, parse, debug, options) {
|
||||
if (onFinished.isFinished(req)) {
|
||||
debug('body already parsed')
|
||||
next()
|
||||
return
|
||||
}
|
||||
|
||||
if (!('body' in req)) {
|
||||
req.body = undefined
|
||||
}
|
||||
|
||||
// skip requests without bodies
|
||||
if (!hasBody(req)) {
|
||||
debug('skip empty body')
|
||||
next()
|
||||
return
|
||||
}
|
||||
|
||||
debug('content-type %j', req.headers['content-type'])
|
||||
|
||||
// determine if request should be parsed
|
||||
if (!options.shouldParse(req)) {
|
||||
debug('skip parsing')
|
||||
next()
|
||||
return
|
||||
}
|
||||
|
||||
let encoding = null
|
||||
if (options?.skipCharset !== true) {
|
||||
encoding = getCharset(req) || options.defaultCharset
|
||||
|
||||
// validate charset
|
||||
if (!!options?.isValidCharset && !options.isValidCharset(encoding)) {
|
||||
debug('invalid charset')
|
||||
next(createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', {
|
||||
charset: encoding,
|
||||
type: 'charset.unsupported'
|
||||
}))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
let length
|
||||
const opts = options
|
||||
let stream
|
||||
|
||||
// read options
|
||||
const verify = opts.verify
|
||||
|
||||
try {
|
||||
// get the content stream
|
||||
stream = contentstream(req, debug, opts.inflate)
|
||||
length = stream.length
|
||||
stream.length = undefined
|
||||
} catch (err) {
|
||||
return next(err)
|
||||
}
|
||||
|
||||
// set raw-body options
|
||||
opts.length = length
|
||||
opts.encoding = verify
|
||||
? null
|
||||
: encoding
|
||||
|
||||
// assert charset is supported
|
||||
if (opts.encoding === null && encoding !== null && !iconv.encodingExists(encoding)) {
|
||||
return next(createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', {
|
||||
charset: encoding.toLowerCase(),
|
||||
type: 'charset.unsupported'
|
||||
}))
|
||||
}
|
||||
|
||||
// read body
|
||||
debug('read body')
|
||||
getBody(stream, opts, function (error, body) {
|
||||
if (error) {
|
||||
let _error
|
||||
|
||||
if (error.type === 'encoding.unsupported') {
|
||||
// echo back charset
|
||||
_error = createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', {
|
||||
charset: encoding.toLowerCase(),
|
||||
type: 'charset.unsupported'
|
||||
})
|
||||
} else {
|
||||
// set status code on error
|
||||
_error = createError(400, error)
|
||||
}
|
||||
|
||||
// unpipe from stream and destroy
|
||||
if (stream !== req) {
|
||||
req.unpipe()
|
||||
stream.destroy()
|
||||
}
|
||||
|
||||
// read off entire request
|
||||
dump(req, function onfinished () {
|
||||
next(createError(400, _error))
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// verify
|
||||
if (verify) {
|
||||
try {
|
||||
debug('verify body')
|
||||
verify(req, res, body, encoding)
|
||||
} catch (err) {
|
||||
next(createError(403, err, {
|
||||
body: body,
|
||||
type: err.type || 'entity.verify.failed'
|
||||
}))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// parse
|
||||
let str = body
|
||||
try {
|
||||
debug('parse body')
|
||||
str = typeof body !== 'string' && encoding !== null
|
||||
? iconv.decode(body, encoding)
|
||||
: body
|
||||
req.body = parse(str, encoding)
|
||||
} catch (err) {
|
||||
next(createError(400, err, {
|
||||
body: str,
|
||||
type: err.type || 'entity.parse.failed'
|
||||
}))
|
||||
return
|
||||
}
|
||||
|
||||
next()
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the content stream of the request.
|
||||
*
|
||||
* @param {Object} req
|
||||
* @param {Function} debug
|
||||
* @param {boolean} inflate
|
||||
* @returns {Object}
|
||||
* @private
|
||||
*/
|
||||
function contentstream (req, debug, inflate) {
|
||||
const encoding = (req.headers['content-encoding'] || 'identity').toLowerCase()
|
||||
const length = req.headers['content-length']
|
||||
|
||||
debug('content-encoding "%s"', encoding)
|
||||
|
||||
if (inflate === false && encoding !== 'identity') {
|
||||
throw createError(415, 'content encoding unsupported', {
|
||||
encoding: encoding,
|
||||
type: 'encoding.unsupported'
|
||||
})
|
||||
}
|
||||
|
||||
if (encoding === 'identity') {
|
||||
req.length = length
|
||||
return req
|
||||
}
|
||||
|
||||
const stream = createDecompressionStream(encoding, debug)
|
||||
req.pipe(stream)
|
||||
return stream
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a decompression stream for the given encoding.
|
||||
* @param {string} encoding
|
||||
* @param {Function} debug
|
||||
* @returns {Object}
|
||||
* @private
|
||||
*/
|
||||
function createDecompressionStream (encoding, debug) {
|
||||
switch (encoding) {
|
||||
case 'deflate':
|
||||
debug('inflate body')
|
||||
return zlib.createInflate()
|
||||
case 'gzip':
|
||||
debug('gunzip body')
|
||||
return zlib.createGunzip()
|
||||
case 'br':
|
||||
debug('brotli decompress body')
|
||||
return zlib.createBrotliDecompress()
|
||||
default:
|
||||
throw createError(415, 'unsupported content encoding "' + encoding + '"', {
|
||||
encoding: encoding,
|
||||
type: 'encoding.unsupported'
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Dump the contents of a request.
|
||||
*
|
||||
* @param {Object} req
|
||||
* @param {Function} callback
|
||||
* @private
|
||||
*/
|
||||
function dump (req, callback) {
|
||||
if (onFinished.isFinished(req)) {
|
||||
callback(null)
|
||||
} else {
|
||||
onFinished(req, callback)
|
||||
req.resume()
|
||||
}
|
||||
}
|
||||
+186
@@ -0,0 +1,186 @@
|
||||
/*!
|
||||
* body-parser
|
||||
* Copyright(c) 2014 Jonathan Ong
|
||||
* Copyright(c) 2014-2015 Douglas Christopher Wilson
|
||||
* MIT Licensed
|
||||
*/
|
||||
|
||||
'use strict'
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
* @private
|
||||
*/
|
||||
|
||||
const debug = require('debug')('body-parser:json')
|
||||
const read = require('../read')
|
||||
const { normalizeOptions } = require('../utils')
|
||||
|
||||
/**
|
||||
* Module exports.
|
||||
*/
|
||||
|
||||
module.exports = json
|
||||
|
||||
/**
|
||||
* RegExp to match the first non-space in a string.
|
||||
*
|
||||
* Allowed whitespace is defined in RFC 7159:
|
||||
*
|
||||
* ws = *(
|
||||
* %x20 / ; Space
|
||||
* %x09 / ; Horizontal tab
|
||||
* %x0A / ; Line feed or New line
|
||||
* %x0D ) ; Carriage return
|
||||
*/
|
||||
const FIRST_CHAR_REGEXP = /^[\x20\x09\x0a\x0d]*([^\x20\x09\x0a\x0d])/ // eslint-disable-line no-control-regex
|
||||
|
||||
const JSON_SYNTAX_CHAR = '#'
|
||||
const JSON_SYNTAX_REGEXP = /#+/g
|
||||
|
||||
/**
|
||||
* Create a middleware to parse JSON bodies.
|
||||
*
|
||||
* @param {Object} [options]
|
||||
* @returns {Function}
|
||||
* @public
|
||||
*/
|
||||
function json (options) {
|
||||
const normalizedOptions = normalizeOptions(options, 'application/json')
|
||||
|
||||
const parse = createJsonParser(options)
|
||||
|
||||
const readOptions = {
|
||||
...normalizedOptions,
|
||||
// assert charset per RFC 7159 sec 8.1
|
||||
isValidCharset: (charset) => charset.slice(0, 4) === 'utf-'
|
||||
}
|
||||
|
||||
return function jsonParser (req, res, next) {
|
||||
read(req, res, next, parse, debug, readOptions)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a JSON parse function
|
||||
*
|
||||
* @param {object} [options]
|
||||
* @return {function}
|
||||
* @private
|
||||
*/
|
||||
function createJsonParser (options) {
|
||||
const reviver = options?.reviver
|
||||
const strict = options?.strict !== false
|
||||
|
||||
if (strict) {
|
||||
return function parse (body) {
|
||||
if (body.length === 0) {
|
||||
// special-case empty json body, as it's a common client-side mistake
|
||||
// TODO: maybe make this configurable or part of "strict" option
|
||||
return {}
|
||||
}
|
||||
|
||||
const first = firstchar(body)
|
||||
if (first !== '{' && first !== '[') {
|
||||
debug('strict violation')
|
||||
throw createStrictSyntaxError(body, first)
|
||||
}
|
||||
|
||||
try {
|
||||
debug('parse json')
|
||||
return JSON.parse(body, reviver)
|
||||
} catch (e) {
|
||||
throw normalizeJsonSyntaxError(e, {
|
||||
message: e.message,
|
||||
stack: e.stack
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return function parse (body) {
|
||||
if (body.length === 0) {
|
||||
// special-case empty json body, as it's a common client-side mistake
|
||||
// TODO: maybe make this configurable or part of "strict" option
|
||||
return {}
|
||||
}
|
||||
|
||||
try {
|
||||
debug('parse json')
|
||||
return JSON.parse(body, reviver)
|
||||
} catch (e) {
|
||||
throw normalizeJsonSyntaxError(e, {
|
||||
message: e.message,
|
||||
stack: e.stack
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create strict violation syntax error matching native error.
|
||||
*
|
||||
* @param {string} str
|
||||
* @param {string} char
|
||||
* @returns {Error}
|
||||
* @private
|
||||
*/
|
||||
function createStrictSyntaxError (str, char) {
|
||||
const index = str.indexOf(char)
|
||||
let partial = ''
|
||||
|
||||
if (index !== -1) {
|
||||
partial = str.substring(0, index) + JSON_SYNTAX_CHAR.repeat(str.length - index)
|
||||
}
|
||||
|
||||
try {
|
||||
JSON.parse(partial); /* istanbul ignore next */ throw new SyntaxError('strict violation')
|
||||
} catch (e) {
|
||||
return normalizeJsonSyntaxError(e, {
|
||||
message: e.message.replace(JSON_SYNTAX_REGEXP, function (placeholder) {
|
||||
return str.substring(index, index + placeholder.length)
|
||||
}),
|
||||
stack: e.stack
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the first non-whitespace character in a string.
|
||||
*
|
||||
* @param {string} str
|
||||
* @returns {string|undefined}
|
||||
* @private
|
||||
*/
|
||||
function firstchar (str) {
|
||||
const match = FIRST_CHAR_REGEXP.exec(str)
|
||||
|
||||
return match
|
||||
? match[1]
|
||||
: undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a SyntaxError for JSON.parse.
|
||||
*
|
||||
* @param {SyntaxError} error
|
||||
* @param {Object} obj
|
||||
* @returns {SyntaxError}
|
||||
* @private
|
||||
*/
|
||||
function normalizeJsonSyntaxError (error, obj) {
|
||||
const keys = Object.getOwnPropertyNames(error)
|
||||
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
const key = keys[i]
|
||||
if (key !== 'stack' && key !== 'message') {
|
||||
delete error[key]
|
||||
}
|
||||
}
|
||||
|
||||
// replace stack before message for Node.js 0.10 and below
|
||||
error.stack = obj.stack.replace(error.message, obj.message)
|
||||
error.message = obj.message
|
||||
|
||||
return error
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
/*!
|
||||
* body-parser
|
||||
* Copyright(c) 2014-2015 Douglas Christopher Wilson
|
||||
* MIT Licensed
|
||||
*/
|
||||
|
||||
'use strict'
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
const debug = require('debug')('body-parser:raw')
|
||||
const read = require('../read')
|
||||
const { normalizeOptions, passthrough } = require('../utils')
|
||||
|
||||
/**
|
||||
* Module exports.
|
||||
*/
|
||||
|
||||
module.exports = raw
|
||||
|
||||
/**
|
||||
* Create a middleware to parse raw bodies.
|
||||
*
|
||||
* @param {Object} [options]
|
||||
* @returns {Function}
|
||||
* @public
|
||||
*/
|
||||
function raw (options) {
|
||||
const normalizedOptions = normalizeOptions(options, 'application/octet-stream')
|
||||
|
||||
const readOptions = {
|
||||
...normalizedOptions,
|
||||
// Skip charset validation and parse the body as is
|
||||
skipCharset: true
|
||||
}
|
||||
|
||||
return function rawParser (req, res, next) {
|
||||
read(req, res, next, passthrough, debug, readOptions)
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
/*!
|
||||
* body-parser
|
||||
* Copyright(c) 2014-2015 Douglas Christopher Wilson
|
||||
* MIT Licensed
|
||||
*/
|
||||
|
||||
'use strict'
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
const debug = require('debug')('body-parser:text')
|
||||
const read = require('../read')
|
||||
const { normalizeOptions, passthrough } = require('../utils')
|
||||
|
||||
/**
|
||||
* Module exports.
|
||||
*/
|
||||
|
||||
module.exports = text
|
||||
|
||||
/**
|
||||
* Create a middleware to parse text bodies.
|
||||
*
|
||||
* @param {Object} [options]
|
||||
* @returns {Function}
|
||||
* @public
|
||||
*/
|
||||
function text (options) {
|
||||
const normalizedOptions = normalizeOptions(options, 'text/plain')
|
||||
|
||||
return function textParser (req, res, next) {
|
||||
read(req, res, next, passthrough, debug, normalizedOptions)
|
||||
}
|
||||
}
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
/*!
|
||||
* body-parser
|
||||
* Copyright(c) 2014 Jonathan Ong
|
||||
* Copyright(c) 2014-2015 Douglas Christopher Wilson
|
||||
* MIT Licensed
|
||||
*/
|
||||
|
||||
'use strict'
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
* @private
|
||||
*/
|
||||
|
||||
const createError = require('http-errors')
|
||||
const debug = require('debug')('body-parser:urlencoded')
|
||||
const read = require('../read')
|
||||
const qs = require('qs')
|
||||
const { normalizeOptions } = require('../utils')
|
||||
|
||||
/**
|
||||
* Module exports.
|
||||
*/
|
||||
|
||||
module.exports = urlencoded
|
||||
|
||||
/**
|
||||
* Create a middleware to parse urlencoded bodies.
|
||||
*
|
||||
* @param {Object} [options]
|
||||
* @returns {Function}
|
||||
* @public
|
||||
*/
|
||||
function urlencoded (options) {
|
||||
const normalizedOptions = normalizeOptions(options, 'application/x-www-form-urlencoded')
|
||||
|
||||
if (normalizedOptions.defaultCharset !== 'utf-8' && normalizedOptions.defaultCharset !== 'iso-8859-1') {
|
||||
throw new TypeError('option defaultCharset must be either utf-8 or iso-8859-1')
|
||||
}
|
||||
|
||||
// create the appropriate query parser
|
||||
const parse = createQueryParser(options)
|
||||
|
||||
const readOptions = {
|
||||
...normalizedOptions,
|
||||
// assert charset
|
||||
isValidCharset: (charset) => charset === 'utf-8' || charset === 'iso-8859-1'
|
||||
}
|
||||
|
||||
return function urlencodedParser (req, res, next) {
|
||||
read(req, res, next, parse, debug, readOptions)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the extended query parser.
|
||||
*
|
||||
* @param {Object} options
|
||||
* @returns {Function}
|
||||
* @private
|
||||
*/
|
||||
function createQueryParser (options) {
|
||||
const extended = Boolean(options?.extended)
|
||||
let parameterLimit = options?.parameterLimit !== undefined
|
||||
? options?.parameterLimit
|
||||
: 1000
|
||||
const charsetSentinel = options?.charsetSentinel
|
||||
const interpretNumericEntities = options?.interpretNumericEntities
|
||||
const depth = extended ? (options?.depth !== undefined ? options?.depth : 32) : 0
|
||||
|
||||
if (isNaN(parameterLimit) || parameterLimit < 1) {
|
||||
throw new TypeError('option parameterLimit must be a positive number')
|
||||
}
|
||||
|
||||
if (isNaN(depth) || depth < 0) {
|
||||
throw new TypeError('option depth must be a zero or a positive number')
|
||||
}
|
||||
|
||||
if (isFinite(parameterLimit)) {
|
||||
parameterLimit = parameterLimit | 0
|
||||
}
|
||||
|
||||
return function parse (body, encoding) {
|
||||
if (!body.length) return {}
|
||||
|
||||
const paramCount = parameterCount(body, parameterLimit)
|
||||
|
||||
if (paramCount === undefined) {
|
||||
debug('too many parameters')
|
||||
throw createError(413, 'too many parameters', {
|
||||
type: 'parameters.too.many'
|
||||
})
|
||||
}
|
||||
|
||||
const arrayLimit = extended ? Math.max(100, paramCount) : paramCount
|
||||
|
||||
debug('parse ' + (extended ? 'extended ' : '') + 'urlencoding')
|
||||
try {
|
||||
return qs.parse(body, {
|
||||
allowPrototypes: true,
|
||||
arrayLimit: arrayLimit,
|
||||
depth: depth,
|
||||
charsetSentinel: charsetSentinel,
|
||||
interpretNumericEntities: interpretNumericEntities,
|
||||
charset: encoding,
|
||||
parameterLimit: parameterLimit,
|
||||
strictDepth: true
|
||||
})
|
||||
} catch (err) {
|
||||
if (err instanceof RangeError) {
|
||||
throw createError(400, 'The input exceeded the depth', {
|
||||
type: 'querystring.parse.rangeError'
|
||||
})
|
||||
} else {
|
||||
throw err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Count the number of parameters, stopping once limit reached
|
||||
*
|
||||
* @param {string} body
|
||||
* @param {number} limit
|
||||
* @returns {number|undefined} Returns undefined if limit exceeded
|
||||
* @private
|
||||
*/
|
||||
function parameterCount (body, limit) {
|
||||
let count = 0
|
||||
let index = -1
|
||||
do {
|
||||
count++
|
||||
if (count > limit) return undefined // Early exit if limit exceeded
|
||||
index = body.indexOf('&', index + 1)
|
||||
} while (index !== -1)
|
||||
return count
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
'use strict'
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
const bytes = require('bytes')
|
||||
const contentType = require('content-type')
|
||||
const typeis = require('type-is')
|
||||
|
||||
/**
|
||||
* Module exports.
|
||||
*/
|
||||
module.exports = {
|
||||
getCharset,
|
||||
normalizeOptions,
|
||||
passthrough
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the charset of a request.
|
||||
*
|
||||
* @param {Object} req
|
||||
* @returns {string | undefined}
|
||||
* @private
|
||||
*/
|
||||
function getCharset (req) {
|
||||
const header = req.headers['content-type']
|
||||
if (!header) return undefined
|
||||
return contentType.parse(header).parameters.charset?.toLowerCase()
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the simple type checker.
|
||||
*
|
||||
* @param {string | string[]} type
|
||||
* @returns {Function}
|
||||
* @private
|
||||
*/
|
||||
function typeChecker (type) {
|
||||
return function checkType (req) {
|
||||
return Boolean(typeis(req, type))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes the common options for all parsers.
|
||||
*
|
||||
* @param {Object} options options to normalize
|
||||
* @param {string | string[] | Function} defaultType default content type(s) or a function to determine it
|
||||
* @returns {Object}
|
||||
* @private
|
||||
*/
|
||||
function normalizeOptions (options, defaultType) {
|
||||
if (!defaultType) {
|
||||
// Parsers must define a default content type
|
||||
throw new TypeError('defaultType must be provided')
|
||||
}
|
||||
|
||||
const inflate = options?.inflate !== false
|
||||
const limit = typeof options?.limit === 'undefined' || options?.limit === null
|
||||
? 102400 // 100kb default
|
||||
: bytes.parse(options.limit)
|
||||
const type = options?.type || defaultType
|
||||
const verify = options?.verify || false
|
||||
const defaultCharset = options?.defaultCharset || 'utf-8'
|
||||
|
||||
if (limit === null) {
|
||||
throw new TypeError(`option limit "${String(options.limit)}" is invalid`)
|
||||
}
|
||||
|
||||
if (verify !== false && typeof verify !== 'function') {
|
||||
throw new TypeError('option verify must be function')
|
||||
}
|
||||
|
||||
// create the appropriate type checking function
|
||||
const shouldParse = typeof type !== 'function'
|
||||
? typeChecker(type)
|
||||
: type
|
||||
|
||||
return {
|
||||
inflate,
|
||||
limit,
|
||||
verify,
|
||||
defaultCharset,
|
||||
shouldParse
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Passthrough function that returns input unchanged.
|
||||
* Used by parsers that don't need to transform the data.
|
||||
*
|
||||
* @param {*} value
|
||||
* @returns {*}
|
||||
* @private
|
||||
*/
|
||||
function passthrough (value) {
|
||||
return value
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
(The MIT License)
|
||||
|
||||
Copyright (c) 2015 Douglas Christopher Wilson
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
'Software'), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
|
||||
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
||||
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
# content-type
|
||||
|
||||
[![NPM version][npm-image]][npm-url]
|
||||
[![NPM downloads][downloads-image]][downloads-url]
|
||||
[![Build status][build-image]][build-url]
|
||||
[![Build coverage][coverage-image]][coverage-url]
|
||||
[![License][license-image]][license-url]
|
||||
|
||||
Create and parse HTTP `Content-Type` header.
|
||||
|
||||
## Installation
|
||||
|
||||
```sh
|
||||
npm install content-type
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
```js
|
||||
const contentType = require("content-type");
|
||||
```
|
||||
|
||||
### contentType.parse(string, options?)
|
||||
|
||||
```js
|
||||
const obj = contentType.parse("image/svg+xml; charset=utf-8");
|
||||
```
|
||||
|
||||
Parse a `Content-Type` header. This will return an object with the following properties (examples are shown for the string `'image/svg+xml; charset=utf-8'`):
|
||||
|
||||
- `type`: The media type. Example: `'image/svg+xml'`.
|
||||
- `parameters`: An object of the parameters in the media type (parameter name is always lower case). Example: `{charset: 'utf-8'}`.
|
||||
|
||||
The parser is lenient and does not error. You should validate `type` and `parameters` before trusting them.
|
||||
|
||||
#### Options
|
||||
|
||||
- `parameters` (default: `true`): Set to `false` to skip parameters.
|
||||
|
||||
### contentType.format(obj)
|
||||
|
||||
```js
|
||||
const str = contentType.format({
|
||||
type: "image/svg+xml",
|
||||
parameters: { charset: "utf-8" },
|
||||
});
|
||||
```
|
||||
|
||||
Format an object into a `Content-Type` header. This will return a string of the content type for the given object with the following properties (examples are shown that produce the string `'image/svg+xml; charset=utf-8'`):
|
||||
|
||||
- `type`: The media type. Example: `'image/svg+xml'`.
|
||||
- `parameters`: An optional object of the parameters in the media type. Example: `{charset: 'utf-8'}`.
|
||||
|
||||
Throws a `TypeError` if the object contains an invalid type or parameter names.
|
||||
|
||||
## License
|
||||
|
||||
[MIT](LICENSE)
|
||||
|
||||
[npm-image]: https://img.shields.io/npm/v/content-type
|
||||
[npm-url]: https://npmjs.org/package/content-type
|
||||
[downloads-image]: https://img.shields.io/npm/dm/content-type
|
||||
[downloads-url]: https://npmjs.org/package/content-type
|
||||
[build-image]: https://img.shields.io/github/actions/workflow/status/jshttp/content-type/ci.yml?branch=master
|
||||
[build-url]: https://github.com/jshttp/content-type/actions/workflows/ci.yml?query=branch%3Amaster
|
||||
[coverage-image]: https://img.shields.io/codecov/c/gh/jshttp/content-type
|
||||
[coverage-url]: https://codecov.io/gh/jshttp/content-type
|
||||
[license-image]: http://img.shields.io/npm/l/content-type.svg?style=flat
|
||||
[license-url]: LICENSE
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
/*!
|
||||
* content-type
|
||||
* Copyright(c) 2015 Douglas Christopher Wilson
|
||||
* MIT Licensed
|
||||
*/
|
||||
/**
|
||||
* The content type object contains a type string and optional parameters.
|
||||
*/
|
||||
export interface ContentType {
|
||||
type: string;
|
||||
parameters: Record<string, string>;
|
||||
}
|
||||
/**
|
||||
* Format an object into a `Content-Type` header.
|
||||
*/
|
||||
export declare function format(obj: Partial<ContentType>): string;
|
||||
/**
|
||||
* Options for parsing a `Content-Type` header.
|
||||
*/
|
||||
export interface ParseOptions {
|
||||
parameters?: boolean;
|
||||
}
|
||||
/**
|
||||
* Parse a `Content-Type` header.
|
||||
*/
|
||||
export declare function parse(header: string, options?: ParseOptions): ContentType;
|
||||
+170
@@ -0,0 +1,170 @@
|
||||
"use strict";
|
||||
/*!
|
||||
* content-type
|
||||
* Copyright(c) 2015 Douglas Christopher Wilson
|
||||
* MIT Licensed
|
||||
*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.format = format;
|
||||
exports.parse = parse;
|
||||
const TEXT_REGEXP = /^[\u0009\u0020-\u007e\u0080-\u00ff]*$/;
|
||||
const TOKEN_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
|
||||
/**
|
||||
* RegExp to match chars that must be quoted-pair in RFC 9110 sec 5.6.4
|
||||
*/
|
||||
const QUOTE_REGEXP = /[\\"]/g;
|
||||
/**
|
||||
* RegExp to match type in RFC 9110 sec 8.3.1
|
||||
*
|
||||
* media-type = type "/" subtype
|
||||
* type = token
|
||||
* subtype = token
|
||||
*/
|
||||
const TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
|
||||
/**
|
||||
* Null object perf optimization. Faster than `Object.create(null)` and `{ __proto__: null }`.
|
||||
*/
|
||||
const NullObject = /* @__PURE__ */ (() => {
|
||||
const C = function () { };
|
||||
C.prototype = Object.create(null);
|
||||
return C;
|
||||
})();
|
||||
/**
|
||||
* Format an object into a `Content-Type` header.
|
||||
*/
|
||||
function format(obj) {
|
||||
const { type, parameters } = obj;
|
||||
if (!type || !TYPE_REGEXP.test(type)) {
|
||||
throw new TypeError(`Invalid type: ${type}`);
|
||||
}
|
||||
let result = type;
|
||||
if (parameters) {
|
||||
for (const param of Object.keys(parameters)) {
|
||||
if (!TOKEN_REGEXP.test(param)) {
|
||||
throw new TypeError(`Invalid parameter name: ${param}`);
|
||||
}
|
||||
result += `; ${param}=${qstring(parameters[param])}`;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
/**
|
||||
* Parse a `Content-Type` header.
|
||||
*/
|
||||
function parse(header, options) {
|
||||
const len = header.length;
|
||||
let index = skipOWS(header, 0, len);
|
||||
const valueStart = index;
|
||||
index = skipValue(header, index, len);
|
||||
const valueEnd = trailingOWS(header, valueStart, index);
|
||||
const type = header.slice(valueStart, valueEnd).toLowerCase();
|
||||
const parameters = options?.parameters === false
|
||||
? new NullObject()
|
||||
: parseParameters(header, index, len);
|
||||
return { type, parameters };
|
||||
}
|
||||
const SP = 32; // " "
|
||||
const HTAB = 9; // "\t"
|
||||
const SEMI = 59; // ";"
|
||||
const EQ = 61; // "="
|
||||
const DQUOTE = 34; // '"'
|
||||
const BSLASH = 92; // "\\"
|
||||
/**
|
||||
* Parses the parameters of a `Content-Type` header starting at the given index.
|
||||
*/
|
||||
function parseParameters(header, index, len) {
|
||||
const parameters = new NullObject();
|
||||
parameter: while (index < len) {
|
||||
index = skipOWS(header, index + 1 /* Skip over ; */, len);
|
||||
const keyStart = index;
|
||||
while (index < len) {
|
||||
const code = header.charCodeAt(index);
|
||||
if (code === SEMI)
|
||||
continue parameter;
|
||||
if (code === EQ) {
|
||||
const keyEnd = trailingOWS(header, keyStart, index);
|
||||
const key = header.slice(keyStart, keyEnd).toLowerCase();
|
||||
index = skipOWS(header, index + 1, len);
|
||||
if (index < len && header.charCodeAt(index) === DQUOTE) {
|
||||
index++;
|
||||
let value = "";
|
||||
while (index < len) {
|
||||
const code = header.charCodeAt(index++);
|
||||
if (code === DQUOTE) {
|
||||
index = skipValue(header, index, len);
|
||||
if (parameters[key] === undefined)
|
||||
parameters[key] = value;
|
||||
break;
|
||||
}
|
||||
if (code === BSLASH && index < len) {
|
||||
value += header[index++];
|
||||
continue;
|
||||
}
|
||||
value += String.fromCharCode(code);
|
||||
}
|
||||
continue parameter;
|
||||
}
|
||||
const valueStart = index;
|
||||
index = skipValue(header, index, len);
|
||||
if (parameters[key] === undefined) {
|
||||
const valueEnd = trailingOWS(header, valueStart, index);
|
||||
parameters[key] = header.slice(valueStart, valueEnd);
|
||||
}
|
||||
continue parameter;
|
||||
}
|
||||
index++;
|
||||
}
|
||||
}
|
||||
return parameters;
|
||||
}
|
||||
/**
|
||||
* Skip over characters until a semicolon.
|
||||
*/
|
||||
function skipValue(str, index, len) {
|
||||
while (index < len) {
|
||||
const char = str.charCodeAt(index);
|
||||
if (char === SEMI)
|
||||
break;
|
||||
index++;
|
||||
}
|
||||
return index;
|
||||
}
|
||||
/**
|
||||
* Skip optional whitespace (OWS) in an HTTP header value.
|
||||
*
|
||||
* OWS is defined in RFC 9110 sec 5.6.3 as SP (" ") or HTAB ("\t").
|
||||
*/
|
||||
function skipOWS(header, index, len) {
|
||||
while (index < len) {
|
||||
const char = header.charCodeAt(index);
|
||||
if (char !== SP && char !== HTAB)
|
||||
break;
|
||||
index++;
|
||||
}
|
||||
return index;
|
||||
}
|
||||
/**
|
||||
* Trim optional whitespace (OWS) from the end of a substring.
|
||||
*
|
||||
* OWS is defined in RFC 9110 sec 5.6.3 as SP (" ") or HTAB ("\t").
|
||||
*/
|
||||
function trailingOWS(header, start, end) {
|
||||
while (end > start) {
|
||||
const char = header.charCodeAt(end - 1);
|
||||
if (char !== SP && char !== HTAB)
|
||||
break;
|
||||
end--;
|
||||
}
|
||||
return end;
|
||||
}
|
||||
/**
|
||||
* Serialize a parameter value.
|
||||
*/
|
||||
function qstring(str) {
|
||||
if (TOKEN_REGEXP.test(str))
|
||||
return str;
|
||||
if (TEXT_REGEXP.test(str))
|
||||
return `"${str.replace(QUOTE_REGEXP, "\\$&")}"`;
|
||||
throw new TypeError(`Invalid parameter value: ${str}`);
|
||||
}
|
||||
//# sourceMappingURL=index.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+52
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"name": "content-type",
|
||||
"version": "2.0.0",
|
||||
"description": "Create and parse HTTP Content-Type header",
|
||||
"keywords": [
|
||||
"content-type",
|
||||
"http",
|
||||
"req",
|
||||
"res",
|
||||
"rfc7231",
|
||||
"rfc9110"
|
||||
],
|
||||
"repository": "jshttp/content-type",
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/express"
|
||||
},
|
||||
"license": "MIT",
|
||||
"author": "Douglas Christopher Wilson <doug@somethingdoug.com>",
|
||||
"type": "commonjs",
|
||||
"exports": "./dist/index.js",
|
||||
"main": "./dist/index.js",
|
||||
"typings": "./dist/index.d.ts",
|
||||
"files": [
|
||||
"dist/"
|
||||
],
|
||||
"scripts": {
|
||||
"bench": "vitest bench",
|
||||
"build": "ts-scripts build",
|
||||
"format": "ts-scripts format",
|
||||
"prepare": "ts-scripts install && npm run build",
|
||||
"specs": "ts-scripts specs",
|
||||
"test": "ts-scripts test"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@borderless/ts-scripts": "^0.15.0",
|
||||
"@vitest/coverage-v8": "^3.0.5",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^3.2.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"ts-scripts": {
|
||||
"dist": [
|
||||
"dist"
|
||||
],
|
||||
"project": [
|
||||
"tsconfig.build.json"
|
||||
]
|
||||
}
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
{
|
||||
"name": "body-parser",
|
||||
"description": "Node.js body parsing middleware",
|
||||
"version": "2.3.0",
|
||||
"contributors": [
|
||||
"Douglas Christopher Wilson <doug@somethingdoug.com>",
|
||||
"Jonathan Ong <me@jongleberry.com> (http://jongleberry.com)"
|
||||
],
|
||||
"license": "MIT",
|
||||
"repository": "expressjs/body-parser",
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/express"
|
||||
},
|
||||
"type": "commonjs",
|
||||
"exports": {
|
||||
".": "./index.js",
|
||||
"./package.json": "./package.json",
|
||||
"./json": "./lib/types/json.js",
|
||||
"./raw": "./lib/types/raw.js",
|
||||
"./text": "./lib/types/text.js",
|
||||
"./urlencoded": "./lib/types/urlencoded.js",
|
||||
"./lib/*": "./lib/*.js",
|
||||
"./lib/*.js": "./lib/*.js",
|
||||
"./lib/types/*": "./lib/types/*.js",
|
||||
"./lib/types/*.js": "./lib/types/*.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"bytes": "^3.1.2",
|
||||
"content-type": "^2.0.0",
|
||||
"debug": "^4.4.3",
|
||||
"http-errors": "^2.0.1",
|
||||
"iconv-lite": "^0.7.2",
|
||||
"on-finished": "^2.4.1",
|
||||
"qs": "^6.15.2",
|
||||
"raw-body": "^3.0.2",
|
||||
"type-is": "^2.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"eslint": "^8.57.1",
|
||||
"eslint-config-standard": "^14.1.1",
|
||||
"eslint-plugin-import": "^2.32.0",
|
||||
"eslint-plugin-markdown": "^3.0.1",
|
||||
"eslint-plugin-node": "^11.1.0",
|
||||
"eslint-plugin-promise": "^6.6.0",
|
||||
"eslint-plugin-standard": "^4.1.0",
|
||||
"mocha": "^11.7.6",
|
||||
"nyc": "^17.1.0",
|
||||
"supertest": "^7.2.2"
|
||||
},
|
||||
"files": [
|
||||
"lib/",
|
||||
"LICENSE",
|
||||
"index.js"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"scripts": {
|
||||
"lint": "eslint .",
|
||||
"test": "mocha --reporter spec --check-leaks test/",
|
||||
"test-ci": "nyc --reporter=lcovonly --reporter=text npm test",
|
||||
"test-cov": "nyc --reporter=html --reporter=text npm test"
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user