diff --git a/index.js b/index.js index 8100b23..291414d 100644 --- a/index.js +++ b/index.js @@ -3,6 +3,7 @@ var join = require('url').resolve; var iconv = require('iconv-lite'); var request = require('co-request').defaults({ jar: true }); +var getRawBody = require('raw-body'); module.exports = function(options) { options || (options = {}); @@ -12,6 +13,7 @@ module.exports = function(options) { } return function* proxy(next) { + var body; var url = resolve(this.path, options); // don't match @@ -19,12 +21,21 @@ module.exports = function(options) { return yield* next; } + // get raw request body + if (this.request.length) { + body = yield getRawBody(this.req, { + length: this.request.length, + limit: '1mb', + encoding: this.request.charset + }); + } + var opt = { url: url + '?' + this.querystring, headers: this.header, encoding: null, method: this.method, - body: this.request.body + body: body }; var res = yield request(opt); diff --git a/package.json b/package.json index 92d5d1a..03db72e 100644 --- a/package.json +++ b/package.json @@ -5,7 +5,8 @@ "main": "index", "dependencies": { "iconv-lite": "^0.2.11", - "co-request": "^0.2.0" + "co-request": "^0.2.0", + "raw-body": "^1.3.0" }, "keywords": [ "koa", diff --git a/test/index.js b/test/index.js index 8a93c11..89391dd 100644 --- a/test/index.js +++ b/test/index.js @@ -7,6 +7,7 @@ var request = require('supertest'); var koa = require('koa'); var serve = require('koa-static'); var router = require('koa-router'); +var getRawBody = require('raw-body'); describe('koa-proxy', function() { @@ -213,4 +214,37 @@ describe('koa-proxy', function() { .get('/error') .expect(500, done); }); + + it('should proxy requst body', function(done) { + var destApp = koa(); + destApp.on('error', done); + + // destination app receives proxied request + // assert that request body matches original request body + destApp.use(function* (next) { + var body = yield getRawBody(this.req, { + length: this.request.length, + limit: '1mb', + encoding: this.request.charset + }); + + body.toString().should.equal('some body content'); + done(); + }); + + destApp.listen(1235); + + var app = koa(); + app.use(proxy({ + host: 'http://localhost:1235' + })); + + request(app.listen()) + .post('/') + .send('some body content') + .end(function(err, res) { + if (err) return done(err); + }); + }); + });