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 Koa v1 support
|
15 | ```
|
16 | $ npm install koa-body@3
|
17 | ```
|
18 |
|
19 | ## Breaking Changes in v3/4
|
20 | To address a potential security issue, the `files` property has been moved to `ctx.request.files`. In prior versions, `files` was a property of `ctx.request.body`. If you do not use multipart uploads, no changes to your code need to be made.
|
21 |
|
22 | Versions 1 and 2 of `koa-body` are deprecated and replaced with versions 3 and 4, respectively.
|
23 |
|
24 | ## Features
|
25 | - can handle three type requests
|
26 | * **multipart/form-data**
|
27 | * **application/x-www-urlencoded**
|
28 | * **application/json**
|
29 | - option for patch to Koa or Node, or either
|
30 | - file uploads
|
31 | - body, fields and files limiting
|
32 |
|
33 | ## Hello world
|
34 | ```sh
|
35 | npm install koa
|
36 | npm install koa-body
|
37 | nvm install v8.11.2 # Note - Koa requires node v7.6.0+ for async/await support
|
38 | ```
|
39 | index.js:
|
40 | ```js
|
41 | const Koa = require('koa');
|
42 | const koaBody = require('koa-body');
|
43 |
|
44 | const app = new Koa();
|
45 |
|
46 | app.use(koaBody());
|
47 | app.use(ctx => {
|
48 | ctx.body = `Request Body: ${JSON.stringify(ctx.request.body)}`;
|
49 | });
|
50 |
|
51 | app.listen(3000);
|
52 | ```
|
53 |
|
54 | ```sh
|
55 | $ node index.js
|
56 | $ curl -i http://localhost:3000/users -d "name=test"
|
57 | HTTP/1.1 200 OK
|
58 | Content-Type: text/plain; charset=utf-8
|
59 | Content-Length: 29
|
60 | Date: Wed, 03 May 2017 02:09:44 GMT
|
61 | Connection: keep-alive
|
62 |
|
63 | Request Body: {"name":"test"}%
|
64 | ```
|
65 |
|
66 | **For a more comprehensive example, see** `examples/multipart.js`
|
67 |
|
68 | ## Usage with [koa-router](https://github.com/alexmingoia/koa-router)
|
69 | > 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.
|
70 |
|
71 | ```js
|
72 | const Koa = require('koa');
|
73 | const app = new Koa();
|
74 | const router = require('koa-router')();
|
75 | const koaBody = require('koa-body');
|
76 |
|
77 | router.post('/users', koaBody(),
|
78 | (ctx) => {
|
79 | console.log(ctx.request.body);
|
80 | // => POST body
|
81 | ctx.body = JSON.stringify(ctx.request.body);
|
82 | }
|
83 | );
|
84 |
|
85 | app.use(router.routes());
|
86 |
|
87 | app.listen(3000);
|
88 | console.log('curl -i http://localhost:3000/users -d "name=test"');
|
89 | ```
|
90 |
|
91 |
|
92 | ## Options
|
93 | > Options available for `koa-body`. Four custom options, and others are from `raw-body` and `formidable`.
|
94 |
|
95 | - `patchNode` **{Boolean}** Patch request body to Node's `ctx.req`, default `false`
|
96 | - `patchKoa` **{Boolean}** Patch request body to Koa's `ctx.request`, default `true`
|
97 | - `jsonLimit` **{String|Integer}** The byte (if integer) limit of the JSON body, default `1mb`
|
98 | - `formLimit` **{String|Integer}** The byte (if integer) limit of the form body, default `56kb`
|
99 | - `textLimit` **{String|Integer}** The byte (if integer) limit of the text body, default `56kb`
|
100 | - `encoding` **{String}** Sets encoding for incoming form fields, default `utf-8`
|
101 | - `multipart` **{Boolean}** Parse multipart bodies, default `false`
|
102 | - `urlencoded` **{Boolean}** Parse urlencoded bodies, default `true`
|
103 | - `text` **{Boolean}** Parse text bodies, default `true`
|
104 | - `json` **{Boolean}** Parse json bodies, default `true`
|
105 | - `jsonStrict` **{Boolean}** Toggles co-body strict mode; if set to true - only parses arrays or objects, default `true`
|
106 | - `formidable` **{Object}** Options to pass to the formidable multipart parser
|
107 | - `onError` **{Function}** Custom error handle, if throw an error, you can customize the response - onError(error, context), default will throw
|
108 | - `strict` **{Boolean}** If enabled, don't parse GET, HEAD, DELETE requests, default `true`
|
109 |
|
110 | ## A note about strict mode
|
111 | > 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)
|
112 | - 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.
|
113 | - koa-body is strict by default
|
114 |
|
115 | ## Some options for formidable
|
116 | > See [node-formidable](https://github.com/felixge/node-formidable) for a full list of options
|
117 | - `maxFields` **{Integer}** Limits the number of fields that the querystring parser will decode, default `1000`
|
118 | - `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)`
|
119 | - `uploadDir` **{String}** Sets the directory for placing file uploads in, default `os.tmpDir()`
|
120 | - `keepExtensions` **{Boolean}** Files written to `uploadDir` will include the extensions of the original files, default `false`
|
121 | - `hash` **{String}** If you want checksums calculated for incoming files, set this to either `'sha1'` or `'md5'`, default `false`
|
122 | - `multiples` **{Boolean}** Multiple file uploads or no, default `true`
|
123 | - `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)
|
124 |
|
125 |
|
126 | **Note**: You can patch request body to Node or Koa in same time if you want.
|
127 |
|
128 |
|
129 | ## Tests
|
130 | ```
|
131 | $ npm test
|
132 | ```
|
133 |
|
134 | ## License
|
135 | 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))
|