A full-featured
koabody parser middleware. Supportsmultipart,urlencoded, andjsonrequest bodies. Provides the same functionality as Express's bodyParser -multer.
Install with npm
npm install koa-body
npm install koa koa-body # Note that Koa requires Node.js 7.6.0+ for async/await support
index.js:
const Koa = require('koa');
const { koaBody } = require('koa-body');
const app = new Koa();
app.use(koaBody());
app.use((ctx) => {
ctx.body = `Request Body: ${JSON.stringify(ctx.request.body)}`;
});
app.listen(3000);
node index.js
curl -i http://localhost:3000/users -d "name=test"
Output:
HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8
Content-Length: 29
Date: Wed, 03 May 2017 02:09:44 GMT
Connection: keep-alive
Request Body: {"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.
const Koa = require('koa');
const app = new Koa();
const router = require('@koa/router')();
const { koaBody } = require('koa-body');
router.post('/users', koaBody(), (ctx) => {
console.log(ctx.request.body);
// => POST body
ctx.body = JSON.stringify(ctx.request.body);
});
app.use(router.routes());
app.listen(3000);
console.log('curl -i http://localhost:3000/users -d "name=test"');
For unsupported text body type, for example, text/xml, you can use the unparsed request body at ctx.request.body. For the text content type, the includeUnparsed setting is not required.
// xml-parse.js:
const Koa = require('koa');
const { koaBody } = require('koa-body');
const convert = require('xml-js');
const app = new Koa();
app.use(koaBody());
app.use((ctx) => {
const obj = convert.xml2js(ctx.request.body);
ctx.body = `Request Body: ${JSON.stringify(obj)}`;
});
app.listen(3000);
node xml-parse.js
curl -i http://localhost:3000/users -H "Content-Type: text/xml" -d '<?xml version="1.0"?><catalog id="1"></catalog>'
Output:
HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8
Content-Length: 135
Date: Tue, 09 Jun 2020 11:17:38 GMT
Connection: keep-alive
Request Body: {"declaration":{"attributes":{"version":"1.0"}},"elements":[{"type":"element","name":"catalog","attributes":{"id":"1"}}]}%
Options available for
koa-body. Four custom options, and others are fromco-bodyandformidable.
patchNode {Boolean} Patch request body to Node's ctx.req, default falsepatchKoa {Boolean} Patch request body to Koa's ctx.request, default truejsonLimit {String|Integer} The byte (if integer) limit of the JSON body, default 1mbformLimit {String|Integer} The byte (if integer) limit of the form body, default 56kbtextLimit {String|Integer} The byte (if integer) limit of the text body, default 56kbencoding {String} Sets encoding for incoming form fields, default utf-8multipart {Boolean} Parse multipart bodies, default falseurlencoded {Boolean} Parse urlencoded bodies, default truetext {Boolean} Parse text bodies, such as XML, default truejson {Boolean} Parse JSON bodies, default truejsonStrict {Boolean} Toggles co-body strict mode; if set to true - only parses arrays or objects, default trueincludeUnparsed {Boolean} Toggles co-body returnRawBody option; if set to true, for form encoded and JSON requests the raw, unparsed request body will be attached to ctx.request.rawBody, default falseformidable {Object} Options to pass to the formidable multipart parseronError {Function} Custom error handle, if throw an error, you can customize the response - onError(error, context), default will throwparsedMethods {String[]} Declares the HTTP methods where bodies will be parsed, default ['POST', 'PUT', 'PATCH']. Replaces strict option.parsedMethodssee 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.POST, PUT, and PATCH requestsHttpMethodEnum.PATCHUploaded files are accessible via ctx.request.files.
Some applications require cryptographic verification of request bodies, for example webhooks from slack or stripe. The unparsed body can be accessed if includeUnparsed is true in koa-body's options. Then the unparsed body is available at ctx.request.rawBody. This only works for non multipart bodies.
See node-formidable for a full list of options
maxFields {Integer} Limits the number of fields that the querystring parser will decode, default 1000maxFieldsSize {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 * 1024 * 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 falsehashAlgorithm {String} If you want checksums calculated for incoming files, set this to either 'sha1' or 'md5', default falsemultiples {Boolean} Multiple file uploads or no, default trueonFileBegin {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 docsonPart {Function} Overrides the default onPart of formidable. The function can be used to filter out parts based on their mimetype. For more use cases. See the docsPlease see the Changelog for a summary of changes.
$ npm test
The MIT License, 2014 Charlike Mike Reagent (@tunnckoCore) and Daryl Lau (@daryllau)