nelts-body
A full-featured
koa
body parser middleware. Supportsmultipart
,urlencoded
, andjson
request bodies. Provides the same functionality as Express's bodyParser -multer
. It forks from koa-body
Install
Install with npm
npm install @nelts/nelts-body
Features
- 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 size limiting
Hello World - Quickstart
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
koa-router
Usage withIt'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"');
Usage with nelts
import { Extra, Decorator, Component, Plugin } from '@nelts/nelts';
@Decorator.Controller.Prefix()
export default class Demo extends Component.Controller {
constructor(plugin: Plugin) {
super(plugin);
}
@Decorator.Controller.Request.Dynamic.Loader(Extra.Body(...))
async Home(ctx) {
// ctx.request.body;
// ctx.request.files;
ctx.body = {
body: ctx.request.body,
files: ctx.request.files,
}
}
}
Options
Options available for
koa-body
. Four custom options, and others are fromraw-body
andformidable
.
-
patchNode
{Boolean} Patch request body to Node'sctx.req
, defaultfalse
-
patchKoa
{Boolean} Patch request body to Koa'sctx.request
, defaulttrue
-
jsonLimit
{String|Integer} The byte (if integer) limit of the JSON body, default1mb
-
formLimit
{String|Integer} The byte (if integer) limit of the form body, default56kb
-
textLimit
{String|Integer} The byte (if integer) limit of the text body, default56kb
-
encoding
{String} Sets encoding for incoming form fields, defaultutf-8
-
multipart
{Boolean} Parse multipart bodies, defaultfalse
-
urlencoded
{Boolean} Parse urlencoded bodies, defaulttrue
-
text
{Boolean} Parse text bodies, defaulttrue
-
json
{Boolean} Parse json bodies, defaulttrue
-
jsonStrict
{Boolean} Toggles co-body strict mode; if set to true - only parses arrays or objects, defaulttrue
-
includeUnparsed
{Boolean} Toggles co-body returnRawBody option; if set to true, for form encodedand and JSON requests the raw, unparsed requesty body will be attached toctx.reqeust.body
using aSymbol
, defaultfalse
-
formidable
{Object} Options to pass to the formidable multipart parser -
onError
{Function} Custom error handle, if throw an error, you can customize the response - onError(error, context), default will throw -
strict
{Boolean} DEPRECATED If enabled, don't parse GET, HEAD, DELETE requests, defaulttrue
-
parsedMethods
{String[]} Declares the HTTP methods where bodies will be parsed, default['POST', 'PUT', 'PATCH']
. Replacesstrict
option.
parsedMethods
A note about see http://tools.ietf.org/html/draft-ietf-httpbis-p2-semantics-19#section-6.3
-
GET
,HEAD
, andDELETE
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, parsing only
POST
,PUT
, andPATCH
requests
A note about unparsed request bodies
Some applications require crytopgraphic 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. When enabled, import the symbol for accessing the request body from unparsed = require('koa-body/unparsed.js')
, or define your own accessor using unparsed = Symbol.for('unparsedBody')
. Then the unparsed body is available using ctx.request.body[unparsed]
.
Some options for formidable
See node-formidable for a full list of options
-
maxFields
{Integer} Limits the number of fields that the querystring parser will decode, default1000
-
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, default2mb (2 * 1024 * 1024)
-
uploadDir
{String} Sets the directory for placing file uploads in, defaultos.tmpDir()
-
keepExtensions
{Boolean} Files written touploadDir
will include the extensions of the original files, defaultfalse
-
hash
{String} If you want checksums calculated for incoming files, set this to either'sha1'
or'md5'
, defaultfalse
-
multiples
{Boolean} Multiple file uploads or no, defaulttrue
-
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
Changelog
Please see the Changelog for a summary of changes.
Tests
$ npm test
License
The MIT License, 2014 Charlike Mike Reagent (@tunnckoCore) and Daryl Lau (@daryllau)