1 | koa-body [![Build Status](https://travis-ci.org/dlau/koa-body.svg?branch=koa2)](https://travis-ci.org/dlau/koa-body) [![Dependencies Status](https://david-dm.org/dlau/koa-body/status.svg)](https://david-dm.org/dlau/koa-body)
|
2 | ================
|
3 |
|
4 | > A full-featured [`koa`](https://github.com/koajs/koa) body parser middleware. Support `multipart`, `urlencoded` and `json` request bodies. Provides same functionality as Express's bodyParser - [`multer`](https://github.com/expressjs/multer). And all that is wrapped only around
|
5 | [`co-body`](https://github.com/visionmedia/co-body) and [`formidable`](https://github.com/felixge/node-formidable).
|
6 |
|
7 | ## Install
|
8 | >Install with [npm](https://github.com/npm/npm)
|
9 |
|
10 | ```
|
11 | $ npm install koa-body
|
12 | ```
|
13 |
|
14 | ## Legacy Koa1 support
|
15 | ```
|
16 | $ npm install koa-body@1
|
17 | ```
|
18 |
|
19 | ## Features
|
20 | - can handle three type requests
|
21 | * **multipart/form-data**
|
22 | * **application/x-www-urlencoded**
|
23 | * **application/json**
|
24 | - option for patch to Koa or Node, or either
|
25 | - file uploads
|
26 | - body, fields and files limiting
|
27 |
|
28 | ## Hello world
|
29 | ```sh
|
30 | npm install koa
|
31 | npm install koa-body
|
32 | nvm install v7.9.0 #Note - koa requires node v7.6.0 for ES2015/async support
|
33 | ```
|
34 | index.js:
|
35 | ```js
|
36 | const Koa = require('koa');
|
37 | const koaBody = require('koa-body');
|
38 |
|
39 | const app = new Koa();
|
40 |
|
41 | app.use(koaBody());
|
42 | app.use(ctx => {
|
43 | ctx.body = `Request Body: ${JSON.stringify(ctx.request.body)}`;
|
44 | });
|
45 |
|
46 | app.listen(3000);
|
47 | ```
|
48 |
|
49 | ```sh
|
50 | $ node index.js
|
51 | $ curl -i http://localhost:3000/users -d "name=test"
|
52 | HTTP/1.1 200 OK
|
53 | Content-Type: text/plain; charset=utf-8
|
54 | Content-Length: 29
|
55 | Date: Wed, 03 May 2017 02:09:44 GMT
|
56 | Connection: keep-alive
|
57 |
|
58 | Request Body: {"name":"test"}%
|
59 | ```
|
60 |
|
61 | **For a more comprehensive example, see** `examples/multipart.js`
|
62 |
|
63 | ## Usage with [koa-router](https://github.com/alexmingoia/koa-router)
|
64 | > 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.
|
65 |
|
66 | ```js
|
67 | const Koa = require('koa');
|
68 | const app = new Koa();
|
69 | const router = require('koa-router')();
|
70 | const koaBody = require('koa-body');
|
71 |
|
72 | router.post('/users', koaBody(),
|
73 | (ctx) => {
|
74 | console.log(ctx.request.body);
|
75 | // => POST body
|
76 | ctx.body = JSON.stringify(ctx.request.body);
|
77 | }
|
78 | );
|
79 |
|
80 | app.use(router.routes());
|
81 |
|
82 | app.listen(3000);
|
83 | console.log('curl -i http://localhost:3000/users -d "name=test"');
|
84 | ```
|
85 |
|
86 |
|
87 | ## Options
|
88 | > Options available for `koa-body`. Four custom options, and others are from `raw-body` and `formidable`.
|
89 |
|
90 | - `patchNode` **{Boolean}** Patch request body to Node's `ctx.req`, default `false`
|
91 | - `patchKoa` **{Boolean}** Patch request body to Koa's `ctx.request`, default `true`
|
92 | - `jsonLimit` **{String|Integer}** The byte (if integer) limit of the JSON body, default `1mb`
|
93 | - `formLimit` **{String|Integer}** The byte (if integer) limit of the form body, default `56kb`
|
94 | - `textLimit` **{String|Integer}** The byte (if integer) limit of the text body, default `56kb`
|
95 | - `encoding` **{String}** Sets encoding for incoming form fields, default `utf-8`
|
96 | - `multipart` **{Boolean}** Parse multipart bodies, default `false`
|
97 | - `urlencoded` **{Boolean}** Parse urlencoded bodies, default `true`
|
98 | - `text` **{Boolean}** Parse text bodies, default `true`
|
99 | - `json` **{Boolean}** Parse json bodies, default `true`
|
100 | - `formidable` **{Object}** Options to pass to the formidable multipart parser
|
101 | - `onError` **{Function}** Custom error handle, if throw an error, you can customize the response - onError(error, context), default will throw
|
102 | - `strict` **{Boolean}** If enabled, don't parse GET, HEAD, DELETE requests, default `true`
|
103 |
|
104 | ## A note about strict mode
|
105 | > see [http://tools.ietf.org/html/draft-ietf-httpbis-p2-semantics-19#section-6.3](http://tools.ietf.org/html/draft-ietf-httpbis-p2-semantics-19#section-6.3)
|
106 | - 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.
|
107 | - koa-body is strict by default
|
108 |
|
109 | ## Some options for formidable
|
110 | > See [node-formidable](https://github.com/felixge/node-formidable) for a full list of options
|
111 | - `bytesExpected` **{Integer}** The expected number of bytes in this form, default `null`
|
112 | - `maxFields` **{Integer}** Limits the number of fields that the querystring parser will decode, default `1000`
|
113 | - `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 * 1024 * 1024)`
|
114 | - `uploadDir` **{String}** Sets the directory for placing file uploads in, default `os.tmpDir()`
|
115 | - `keepExtensions` **{Boolean}** Files written to `uploadDir` will include the extensions of the original files, default `false`
|
116 | - `hash` **{String}** If you want checksums calculated for incoming files, set this to either `'sha1'` or `'md5'`, default `false`
|
117 | - `multiples` **{Boolean}** Multiple file uploads or no, default `true`
|
118 | - `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](https://github.com/felixge/node-formidable#filebegin)
|
119 |
|
120 |
|
121 | **Note**: You can patch request body to Node or Koa in same time if you want.
|
122 |
|
123 |
|
124 | ## Tests
|
125 | ```
|
126 | $ npm test
|
127 | ```
|
128 |
|
129 | ## License
|
130 | The MIT License, 2014 [Charlike Mike Reagent](https://github.com/tunnckoCore) ([@tunnckoCore](https://twitter.com/tunnckoCore)) and [Daryl Lau](https://github.com/dlau) ([@daryllau](https://twitter.com/daryllau))
|