|
5 years ago | |
---|---|---|
.. | ||
node_modules | 5 years ago | |
History.md | 5 years ago | |
LICENSE | 5 years ago | |
README.md | 5 years ago | |
index.js | 5 years ago | |
package.json | 5 years ago |
A body parser for koa, base on co-body. support json
, form
and text
type body.
var koa = require('koa');
var bodyParser = require('koa-bodyparser');
var app = koa();
app.use(bodyParser());
app.use(function *() {
// the parsed body will store in this.request.body
// if nothing was parsed, body will be an empty object {}
this.body = this.request.body;
});
['json', 'form']
.utf-8
by co-body
.urlencoded
body. If the body ends up being larger than this limit, a 413 error code is returned. Default is 56kb
.json
body. Default is 1mb
.text
body. Default is 1mb
.true
. See strict mode in co-body
. In strict mode, this.request.body
will always be an object(or array), this avoid lots of type judging. But text body will always return string type.null
. app.use(bodyparser({
detectJSON: function (ctx) {
return /\.json$/i.test(ctx.path);
}
}));
app.use(bodyparser({
extendTypes: {
json: ['application/x-javascript'] // will parse application/x-javascript type body as a JSON string
}
}));
koa-bodyparser
throw an error, you can customize the response like: app.use(bodyparser({
onerror: function (err, ctx) {
ctx.throw('body parse error', 422);
}
}));
this.disableBodyParser = true
.app.use(function* disableBodyParser(next) {
if (this.path === '/disable') this.disableBodyParser = true;
return yield next;
});
app.use(bodyparser());
You can access raw request body by this.request.rawBody
after koa-bodyparser
when:
koa-bodyparser
parsed the request body.this.request.rawBody
is not present before koa-bodyparser
.