What is koa-body?
koa-body is a middleware for Koa that parses incoming request bodies in various formats, including JSON, URL-encoded, and multipart forms. It simplifies handling file uploads and form submissions in Koa applications.
What are koa-body's main functionalities?
JSON Body Parsing
This feature allows you to parse JSON bodies from incoming requests. The middleware automatically parses the JSON and makes it available in `ctx.request.body`.
const Koa = require('koa');
const koaBody = require('koa-body');
const app = new Koa();
app.use(koaBody());
app.use(async ctx => {
if (ctx.method === 'POST') {
ctx.body = `Received JSON data: ${JSON.stringify(ctx.request.body)}`;
} else {
ctx.body = 'Send a POST request with JSON data';
}
});
app.listen(3000);
URL-encoded Body Parsing
This feature allows you to parse URL-encoded bodies from incoming requests. The middleware automatically parses the URL-encoded data and makes it available in `ctx.request.body`.
const Koa = require('koa');
const koaBody = require('koa-body');
const app = new Koa();
app.use(koaBody({ urlencoded: true }));
app.use(async ctx => {
if (ctx.method === 'POST') {
ctx.body = `Received URL-encoded data: ${JSON.stringify(ctx.request.body)}`;
} else {
ctx.body = 'Send a POST request with URL-encoded data';
}
});
app.listen(3000);
Multipart Form Parsing
This feature allows you to parse multipart form data, which is commonly used for file uploads. The middleware automatically parses the multipart data and makes it available in `ctx.request.files`.
const Koa = require('koa');
const koaBody = require('koa-body');
const app = new Koa();
app.use(koaBody({ multipart: true }));
app.use(async ctx => {
if (ctx.method === 'POST') {
const files = ctx.request.files;
ctx.body = `Received files: ${JSON.stringify(files)}`;
} else {
ctx.body = 'Send a POST request with multipart form data';
}
});
app.listen(3000);
Other packages similar to koa-body
koa-bodyparser
koa-bodyparser is a middleware for Koa that parses JSON and URL-encoded request bodies. It is simpler and more lightweight compared to koa-body, but it does not support multipart form data parsing.
koa-multer
koa-multer is a middleware for handling multipart/form-data, which is primarily used for uploading files. It is similar to koa-body in terms of file upload capabilities but does not handle JSON or URL-encoded bodies.
koa-better-body
koa-better-body is a more feature-rich alternative to koa-body, supporting JSON, URL-encoded, and multipart form data parsing. It also offers additional features like custom body parsers and file renaming.
koa-body
A full-feature koa
body parser middleware. Support multipart
, urlencoded
and json
request bodies. Provides same functionality as Express's bodyParser - multer
. And all that is wrapped only around
co-body
and formidable
.
Related module
Install
Install with npm
$ npm install koa-body
Features
- 15 tests
- can handle three type requests
- multipart/form-data
- application/x-www-urlencoded
- application/json
- option for patch to Koa or Node, or either
- file uploads
- body, fields and files limiting
- 2 dependencies only
It's very simple, because you can access the fields and files in the ctx.request.body
or ctx.req.body
JSON object
var app = require('koa')(),
koaBody = require('koa-body');
app.use(koaBody({formidable:{uploadDir: __dirname}}));
app.use(function *(next) {
if (this.request.method == 'POST') {
console.log(this.request.body);
this.body = JSON.stringify(this.request.body);
}
yield next;
});
app.listen(3131)
console.log('curl -i http://localhost:3131/ -d "name=test"');
For a more comprehensive example, see examples/multipart.js
It's generally better to only parse the body as needed, if using a router that supports middleware composition, we can inject it only for certain routes.
var app = require('koa')(),
router = require('koa-router')(),
koaBody = require('koa-body')();
router.post('/users', koaBody,
function *(next) {
console.log(this.request.body);
this.body = JSON.stringify(this.request.body);
}
);
app.use(router.routes());
app.listen(3131);
console.log('curl -i http://localhost:3131/users -d "name=test"');
Options
Options available for koa-body
. Four custom options, and others are from raw-body
and formidable
.
patchNode
{Boolean} Patch request body to Node's ctx.req
, default false
patchKoa
{Boolean} Patch request body to Koa's ctx.request
, default true
jsonLimit
{String|Integer} The byte (if integer) limit of the JSON body, default 1mb
formLimit
{String|Integer} The byte (if integer) limit of the form body, default 56kb
textLimit
{String|Integer} The byte (if integer) limit of the text body, default 56kb
encoding
{String} Sets encoding for incoming form fields, default utf-8
multipart
{Boolean} Parse multipart bodies, default false
urlencoded
{Boolean} Parse urlencoded bodies, default true
text
{Boolean} Parse text bodies, default true
json
{Boolean} Parse json bodies, default true
formidable
{Object} Options to pass to the formidable multipart parserstrict
{Boolean} If enabled, don't parse GET, HEAD, DELETE requests, default true
A note about strict mode
see http://tools.ietf.org/html/draft-ietf-httpbis-p2-semantics-19#section-6.3
- 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.
- koa-body is strict by default
Some options for formidable
See node-formidable for a full list of options
bytesExpected
{Integer} The expected number of bytes in this form, default null
maxFields
{Integer} Limits the number of fields that the querystring parser will decode, default 1000
maxFieldsSize
{Integer} Limits the amount of memory all fields together (except files) can allocate in bytes. If this value is exceeded, an 'error' event is emitted, default 2mb (2 * 2 * 1024)
uploadDir
{String} Sets the directory for placing file uploads in, default os.tmpDir()
keepExtensions
{Boolean} Files written to uploadDir
will include the extensions of the original files, default false
hash
{String} If you want checksums calculated for incoming files, set this to either 'sha1'
or 'md5'
, default false
multiples
{Boolean} Multiple file uploads or no, default true
onFileBegin
{Function} Special callback on file begin. The function is executed directly by formidable. It can be used to rename files before saving them to disk. See the docs
Note: You can patch request body to Node or Koa in same time if you want.
Tests
As usual - npm test
or if you have mocha globally - mocha --harmony-generators
.
$ npm test
License
The MIT License, 2014 Charlike Mike Reagent (@tunnckoCore) and Daryl Lau (@daryllau)