Full-featured [koa][] body parser! Support parsing text, buffer, json, json patch, json api, csp-report, multipart, form and urlencoded bodies. Works for koa@1, koa@2 and will work for koa@3.
npm install koa-better-body> Full-featured [koa][] body parser! Support parsing text, buffer, json, json
> patch, json api, csp-report, multipart, form and urlencoded bodies. Works for
> koa@1, koa@2 and will work for koa@3.
Please consider following this project's author,
Charlike Mike Reagent, and :star: the project
to show your :heart: and support.
[![Code style][codestyle-img]][codestyle-url]
[![CircleCI linux build][linuxbuild-img]][linuxbuild-url]
[![CodeCov coverage status][codecoverage-img]][codecoverage-url]
[![Renovate App Status][renovateapp-img]][renovateapp-url]
[![Make A Pull Request][prs-welcome-img]][prs-welcome-url]
[![Time Since Last Commit][last-commit-img]][last-commit-url]
If you have any _how-to_ kind of questions, please read the [Contributing
Guide][contributing-url] and [Code of Conduct][code_of_conduct-url] documents.
For bugs reports and feature requests, [please create an issue][open-issue-url]
or ping @tunnckoCore at Twitter.
[![Conventional Commits][ccommits-img]][ccommits-url]
[![Minimum Required Nodejs][nodejs-img]][npmv-url]
[![NPM Downloads Monthly][downloads-monthly-img]][npmv-url]
[![NPM Downloads Total][downloads-total-img]][npmv-url]
[![Share Love Tweet][twitter-share-img]][twitter-share-url]
[![Twitter][twitter-img]][twitter-url]
Project is semantically versioned & automatically released
from GitHub Actions with
Lerna.
[![Become a Patron][patreon-img]][patreon-url]
[![Buy me a Kofi][kofi-img]][kofi-url]
[![PayPal Donation][paypal-img]][paypal-url]
[![Bitcoin Coinbase][bitcoin-img]][bitcoin-url]
[![Keybase PGP][keybase-img]][keybase-url]
| Topic | Contact |
| :--------------------------------------------------------------- | ------------------------------------------------: |
| Any legal or licensing questions, like private or commerical use | ![tunnckocore_legal][tunnckocore_legal] |
| For any critical problems and security reports | ![tunnckocore_security][tunnckocore_security] |
| Consulting, professional support, personal or team training | ![tunnckocore_consulting][tunnckocore_consulting] |
| For any questions about Open Source, partnerships and sponsoring | ![tunnckocore_opensource][tunnckocore_opensource] |
- Work for koa@1 and koa@2 (with deprecation messages), will also work in
koa@3 with [koa-convert][]
- Totally flexible through options and absolutely lightweight using
[lazy-cache][]
- Accept few JSON types
- Accept [JSON Patch [RFC6902]](https://tools.ietf.org/html/rfc6902)
(koajs/bodyparser#8)
- Accept JSON API v1
(koajs/bodyparser#7)
- Accept JSON csp-report
(#3)
- Accept text and buffer bodies
- Accept urlencoded and forms bodies
- Accept multipart form data files and fields
- Can parse correctly array data from forms - e.g. multiple fields to have same
name - dlau/koa-body#15
- Can parse correctly forms that accept multiple files - see
#26 and
dlau/koa-body#15
- Strict mode by default - see why on
IETF Message Semantics: Section 6.1
- Custom JSON request detect function -
koajs/bodyparser#f6a5ff
- Custom error handling function -
koajs/bodyparser#19418129
- Extending types of request that your app can accept -
koajs/bodyparser#ba7479b
- Using awesome [formidable][] package -
„battle-tested against hundreds of GB of file uploads“
- Passing a custom formidable.IncomingForm instance, allowing awesome
customization
- Passing all options to formidable.IncomingForm, allowing awesome control
- Install
- API
- koaBetterBody
- Working with koa-router
- Options
- Note about options.extendTypes
- Note about advanced querystring parsing
- Note about strict mode
- See Also
- Contributing
- Guides and Community
- Support the project
- Contributors
- License
_(TOC generated by verb using
markdown-toc)_
This project requires Node.js >=8.11 _(see
Support & Release Policy)_.
Install it using yarn or
npm.
_We highly recommend to use Yarn when you
think to contribute to this project._
``bash`
$ yarn add koa-better-body
_Generated using jest-runner-docs._
> Robust body parser for [koa][]@1, also works for koa@2 (with deprecations).koa@3
> Will also work for future with [koa-convert][].
#### Signature
`ts`
function(options)
#### Params
- options {object} - see more on options sectionreturns
- {GeneratorFunction} - plugin for Koa
#### Examples
`js
var koa = require('koa');
var body = require('koa-better-body');
var app = koa();
app
.use(body())
.use(function* () {
console.log(this.request.body); // if buffer or text
console.log(this.request.files); // if multipart or urlencoded
console.log(this.request.fields); // if json
})
.listen(8080, function () {
console.log('koa server start listening on port 8080');
});
`
using [koa-router][]
`js
'use strict';
var app = require('koa')();
var body = require('koa-better-body');
var router = require('koa-router')();
router.post('/upload', body(), function* (next) {
console.log(this.request.files);
console.log(this.request.fields);
// there's no .body when multipart,urlencoded
// or json request
console.log(this.request.body);
// print it to the API requester
this.body = JSON.stringify(
{
fields: this.request.fields,
files: this.request.files,
body: this.request.body || null,
},
null,
2,
);
yield next;
});
app.use(router.routes());
app.listen(4292);
var format = require('util').format;
var host = 'http://localhost:4292';
var cmd = 'curl -i %s/upload -F "source=@%s/.editorconfig"';
console.log('Try it out with below CURL for koa-better-body repository.');`
console.log(format(cmd, host, __dirname));
Sane defaults. :sparkles:
Accepts JSON, JSON API v1, text, buffer,
csp-report, multipart and
urlencoded/form bodies. If you want to disallow accepting and parsing multipart
body you should pass multipart: false. Most of the defaults you can see atoptions
utils.defaultOptions and utils.defaultTypes. **All are
also been passed to [formidable][].IncomingForm!** Even you can pass
IncomingForm instance to be able to handle the different formidable events.
- fields {Boolean|String}: Default false, which means it will set fieldsthis.request.fields
on . If you pass a string, for example 'foo', you willthis.request.foo
have fields on .files
- {Boolean|String}: Default false, which means it will set filesthis.request.files
on . If you pass a string, for example 'bar', you willthis.request.bar
have files on .multipart
- {Boolean}: Default true. If you pass false it won'ttextLimit
accept/parse multipart bodies.
- {String}: Default '100kb'. Passed to [bytes][].parse method.formLimit
- {String}: Default '100kb'. Passed to [bytes][].parse method.urlencodedLimit
- {String}: Default '100kb'. Alias of opts.formLimit.jsonLimit
- {String}: Default '100kb'. Passed to [bytes][].parse method.bufferLimit
- {String}: Default '1mb'. Passed to [bytes][].parse method.jsonStrict
- {Boolean}: Default true. When set to true, JSON parser willdetectJSON
only accept arrays and objects.
- {Function}: Custom JSON request detect function -detectJSON(ctx)
.strict
- {Boolean}: Default true. Pass false if you want to allowonerror
parsing GET, DELETE and HEAD requests.
- {Function}: Custom error handle, if throw an error, you canonerror(err, ctx)
customize the response - .extendTypes
- {Object}: Default accepting types can find onIncomingForm
utils.defaultTypes function. Allowing you to extend
what your app can accept. By default works for JSON,
JSON API v1, multipart, text, urlencoded and
csp-report.
- {IncomingForm}: Pass an instance offormidable.IncomingForm
to be able to handle formidable events.handler
- {GeneratorFunction}: Works with options.extendTypes.custom tohandler(ctx, options, next)
handle custom types of content-type - . More infoquerystring
below.
- {Object}: Querystring module to be used. By default builtinquerystring
. More info below.qs
- {Object}: Alias of opts.querystring. All opts are also passed todelimiter
[qs][] or querystring module.
- {String}: Default is &. Delimiter of key/value pairs, passedsep
to querystring lib
- {String}: alias of opts.delimiterbuffer
- {Boolean}: Default false, pass true if you want to get body
as buffer.
ExandTypes option gives you a flexible way to handle different content-types and
modify the defaults which can be found
at utils.defaultTypes function. In addition you can pass
combination of options.extendTypes.custom and options.handler. When thehandler
request has some of the "custom" content type, this middleware will call the generator function with ctx, options, next. You can see more at
issue #52.
For example manually handle such content types foo/bar-x, text/quix:
`js
const app = require('koa')()
const body = require('koa-better-body')
app.use(body({
textLimit: '300kb'
extendTypes: {
custom: [
'foo/bar-x',
'text/quix'
]
},
handler: function * (ctx, opts) {
// ctx is equal to this and appopts
// is current options objectkoa-better-body
// passed to this.body
ctx.body = yield this.request.text(opts.textLimit)
}
}))
app.use(function * showBody () {
// is text`
console.log(this.body)
})
parsingBecause this middleware is fully based and integrated with [koa-body-parsers][],
by default it uses Node's built-in module for that thing
querystring. So if you have some
issues with forms, think to add custom querystring module like [qs][] to
options.querystring or app.querystring. Related to this is
issue #45.
Example
`js
const app = require('koa')()
const body = require('koa-better-body')
app.use(body({
multipart: false
querystring: require('qs')
}))
`
It's intentional that it's not included in the deps by default. In v2 it wasapp.querystring
also working by passing it to , because [koa-body-parsers][]
works
that way (index.js#L53).
modeWe are trying to follow standards. :cat2:
You can pass strict:false, but see
IETF HTTP/1.1 Message Semantics: Section 6.1
to understand why we stay to _"strict mode"_ by default. GET, HEAD, and DELETE
requests have no defined semantics for the request body, but this doesn't mean
they may not be valid in certain use cases. Last two tests at
test/options.js are showing usage on non-strict and strict
mode.
Some of these projects are used here or were inspiration for this one, others
are just related. So, thanks for your existance!
- formidable: A node.js module for
parsing form data, especially file uploads. |
homepage
- ip-filter: Validates valid IPs
(IPv4 and IPv6) using [micromatch][] - glob…
more |
homepage using [micromatch][] - glob patterns, RegExp, string or array of globs. If match returns the IP, otherwise null.')
- koa-body-parsers: collection
of koa body parsers |
homepage
- koa-bodyparser: a body parser
for koa |
homepage
- koa-ip-filter: Middleware for
[koa][] that filters IPs against glob patterns, RegExp…
more |
message and custom ID.'" class="text-primary hover:underline" target="_blank" rel="noopener noreferrer">homepage
- koa: Koa web app framework |
homepage
- koala: Koa Framework Suite |
homepage
Please read the [Contributing Guide][contributing-url] and [Code of
Conduct][code_of_conduct-url] documents for advices.
For bug reports and feature requests, please join our [community][community-url]
forum and open a thread there with prefixing the title of the thread with the
name of the project if there's no separate channel for it.
Consider reading the
Support and Release Policy
guide if you are interested in what are the supported Node.js versions and how
we proceed. In short, we support latest two even-numbered Node.js release lines.
[Become a Partner or Sponsor?][kofi-url] :dollar: Check the OpenSource
Commision (tier). :tada: You can get your company logo, link & name on this
file. It's also rendered on package's page in [npmjs.com][npmv-url] and
yarnpkg.com sites too!
:rocket:
Not financial support? Okey!
Pull requests,
stars and all kind of
contributions
are always welcome. :sparkles:
This project follows the
all-contributors
specification. Contributions of any kind are welcome!
Thanks goes to these wonderful people
(emoji key), consider showing
your support to them:
Charlike Mike Reagent 🚇 💻 📖 🤔 🚧 ⚠️ |
Copyright (c) 2014-present, Charlike Mike Reagent
Released under the [MPL-2.0 License][license-url].
[contributing-url]: https://github.com/tunnckoCore/opensource/blob/master/CONTRIBUTING.md
[code_of_conduct-url]: https://github.com/tunnckoCore/opensource/blob/master/CODE_OF_CONDUCT.md
[npmv-url]: https://www.npmjs.com/package/koa-better-body
[npmv-img]: https://badgen.net/npm/v/koa-better-body?icon=npm&cache=300
[license-url]: https://github.com/tunnckoCore/opensource/blob/master/packages/koa-better-body/LICENSE
[license-img]: https://badgen.net/npm/license/koa-better-body?cache=300
[libera-manifesto-url]: https://liberamanifesto.com
[libera-manifesto-img]: https://badgen.net/badge/libera/manifesto/grey
[codecoverage-img]: https://badgen.net/badge/coverage/95.56%25/99CC09?icon=codecov&cache=300
[codecoverage-url]: https://codecov.io/gh/tunnckoCore/opensource
[codestyle-url]: https://github.com/airbnb/javascript
[codestyle-img]: https://badgen.net/badge/code%20style/airbnb/ff5a5f?icon=airbnb&cache=300
[linuxbuild-url]: https://github.com/tunnckocore/opensource/actions
[linuxbuild-img]: https://badgen.net/github/checks/tunnckoCore/opensource/master?cache=300&label=build&icon=github
[ccommits-url]: https://conventionalcommits.org/
[ccommits-img]: https://badgen.net/badge/conventional%20commits/v1.0.0/green?cache=300
[standard-release-url]: https://github.com/standard-release/standard-release
[standard-release-img]: https://badgen.net/badge/semantically/released/05c5ff?cache=300
[community-img]: https://badgen.net/badge/join/community/7b16ff?cache=300
[community-url]: https://github.com/tunnckocorehq/community
[last-commit-img]: https://badgen.net/github/last-commit/tunnckoCore/opensource/master?cache=300
[last-commit-url]: https://github.com/tunnckoCore/opensource/commits/master
[nodejs-img]: https://badgen.net/badge/node/>=8.11/green?cache=300
[downloads-weekly-img]: https://badgen.net/npm/dw/koa-better-body?icon=npm&cache=300
[downloads-monthly-img]: https://badgen.net/npm/dm/koa-better-body?icon=npm&cache=300
[downloads-total-img]: https://badgen.net/npm/dt/koa-better-body?icon=npm&cache=300
[renovateapp-url]: https://renovatebot.com
[renovateapp-img]: https://badgen.net/badge/renovate/enabled/green?cache=300
[prs-welcome-img]: https://badgen.net/badge/PRs/welcome/green?cache=300
[prs-welcome-url]: http://makeapullrequest.com
[paypal-url]: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=HYJJEZNSGAPGC&source=url
[paypal-img]: https://badgen.net/badge/PayPal/donate/003087?cache=300&icon=https://simpleicons.now.sh/paypal/fff
[kofi-url]: https://ko-fi.com/tunnckoCore
[kofi-img]: https://badgen.net/badge/Buy%20me/a%20coffee/29abe0c2?cache=300&icon=https://rawcdn.githack.com/tunnckoCore/badgen-icons/f8264c6414e0bec449dd86f2241d50a9b89a1203/icons/kofi.svg
[bitcoin-url]: https://www.blockchain.com/btc/payment_request?address=3QNHKun1K1SUui1b4Z3KEGPPsWC1TgtnqA&message=Open+Source+Software&amount_local=10¤cy=USD
[bitcoin-img]: https://badgen.net/badge/Bitcoin%20tip/3QNHKun...b4Z3KEGPPsWC1TgtnqA/yellow?cache=300&icon=https://simpleicons.now.sh/bitcoin/fff
[keybase-url]: https://keybase.io/tunnckoCore
[keybase-img]: https://badgen.net/keybase/pgp/tunnckoCore?cache=300
[twitter-url]: https://twitter.com/tunnckoCore
[twitter-img]: https://badgen.net/twitter/follow/tunnckoCore?icon=twitter&color=1da1f2&cache=300
[patreon-url]: https://www.patreon.com/bePatron?u=5579781
[patreon-img]: https://badgen.net/badge/Become/a%20patron/F96854?icon=patreon
[patreon-sponsor-img]: https://badgen.net/badge/become/a%20sponsor/F96854?icon=patreon
[twitter-share-url]: https://twitter.com/intent/tweet?text=https://ghub.now.sh/koa-better-body&via=tunnckoCore
[twitter-share-img]: https://badgen.net/badge/twitter/share/1da1f2?icon=twitter
[open-issue-url]: https://github.com/tunnckoCore/opensource/issues/new
[tunnckocore_legal]: https://badgen.net/https/liam-badge-daknys6gadky.runkit.sh/com/legal/tunnckocore?label&color=A56016&icon=https://svgshare.com/i/Dt6.svg
[tunnckocore_consulting]: https://badgen.net/https/liam-badge-daknys6gadky.runkit.sh/com/consulting/tunnckocore?label&color=07ba96&icon=https://svgshare.com/i/Dt6.svg
[tunnckocore_security]: https://badgen.net/https/liam-badge-daknys6gadky.runkit.sh/com/security/tunnckocore?label&color=ed1848&icon=https://svgshare.com/i/Dt6.svg
[tunnckocore_opensource]: https://badgen.net/https/liam-badge-daknys6gadky.runkit.sh/com/opensource/tunnckocore?label&color=ff7a2f&icon=https://svgshare.com/i/Dt6.svg
[tunnckocore_newsletter]: https://badgen.net/https/liam-badge-daknys6gadky.runkit.sh/com/newsletter/tunnckocore?label&color=5199FF&icon=https://svgshare.com/i/Dt6.svg
[bytes]: https://github.com/visionmedia/bytes.js
[formidable]: https://github.com/node-formidable/formidable
[koa-body-parsers]: https://github.com/koajs/body-parsers
[koa-convert]: https://github.com/gyson/koa-convert
[koa-router]: https://github.com/koajs/router
[koa]: https://github.com/koajs/koa
[lazy-cache]: https://github.com/jonschlinkert/lazy-cache
[micromatch]: https://github.com/micromatch/micromatch
[qs]: https://github.com/ljharb/qs
[raw-body]: https://github.com/stream-utils/raw-body