Skip to content
This repository was archived by the owner on Apr 24, 2019. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {});
Expand All @@ -12,19 +13,29 @@ module.exports = function(options) {
}

return function* proxy(next) {
var body;
var url = resolve(this.path, options);

// don't match
if (!url) {
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);

Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
34 changes: 34 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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() {

Expand Down Expand Up @@ -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);
});
});

});