Koa Body Parser
Form and JSON body parser for Koa.
This purposely does not support multipart request bodies.
It also supports request body limits.
Example
app.use(function (next) {
return function* () {
var body = (yield this.parseJSON) || (yield this.parseUrlencoded)
}
})
API
var koa = require('koa')
var bodyParser = require('koa-body-parser')
var app = koa()
bodyParser(app)
yield this.parseJSON
Parses the JSON body.
If you're a masochist, you can also use a callback:
this.parseJSON(function (err, body) {
})
yield this.parseUrlencoded
Parses the urlencoded body.
Same signature as this.parseJSON
app.strictJSON, this.strictJSON
By default, JSON must be strict.
You may override the default behavior by doing app.strictJSON = false
or this.strictJSON = false
.
this.strictJSON
takes precedent over app.strictJSON
.
app.bodyLimit, this.bodyLimit
Sets the request body limit.
By default, there is no limit.
You can either set it app wide, or context wide.
this.bodyLimit
takes precence over app.bodyLimit
.
You can set it using numerical bytes like app.bodyLimit = 5 * 1024 * 1024
, or you can set it in human readable form like app.bodyLimit = '5mb'
.
For example, you can set a app-wide limit of 100kb
by setting app.bodyLimit = '1mb'
.
Then, perhaps for a route in which users upload an image, you can manually set the limit to this.bodyLimit = '10mb'
.
app.urlencodedParser
By default, url encoded bodies are parsed using the native querystring
module.
If you want to use your own parser, for example the qs
library, you can overwrite this method.
app.urlencodedParser = require('qs').parse
License
The MIT License (MIT)
Copyright (c) 2013 Jonathan Ong me@jongleberry.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.