thomseddon/koa-body-parser — pull request #2 by KjellSchubert (2014-04-14 20:14:20+00:00)
Title: prevent the stalling of requests when using koa-body-parser in nested/mo...

To reproduce the stall problem run the code below, then curl --data "{\"name\":\"foo\"}" http://localhost:3000/things. A trivial solution for this problem is to comment out the line "comment out this line" in the test, in other words to make sure you use only one instance of koa-body-parser in a composite koa app. Still: imo this issue makes nesting/mounting koa apps unnecessarily error-prone. An alternative potential solution for preventing the hang is to check if there's a parsed this.request.body already before doing the yield parse(this.request). I'm not sure if that's a good solution though: if some mounted apps were using koa-body-parser and others were using some alternative like koa-body then this wouldn't prevent the hang. Maybe the problem should be resolved in the underlying co-body package.

var co = require('co');
var koa = require('koa');
var koaMount = require('koa-mount');
var koaRouter = require('koa-router')
var koaBodyParser = require('koa-body-parser');

function getMountableApp() {
var app = koa();
app.use(koaBodyParser()); // comment out this line to prevent a hang
app.use(koaRouter(app));
app.post('/', function * () {
console.log("MountableApp: posted=" + JSON.stringify(this.request.body));
this.body = {MountableApp_posted:this.request.body};
});
return app;
}

var app = koa();

app.use(koaBodyParser());
app.use(koaRouter(app));
app.post('/stuff', function * (next) {
console.log("stuff: posted=" + JSON.stringify(this.request.body));
this.body = {stuff_posted:this.request.body};
});

app.use(koaMount('/things', getMountableApp()));

app.listen(3000);

// test with: curl --data "{\"name\":\"foo\"}" http://localhost:3000/things