Question

I have KOA Like below :

var koa = require('koa'),
bodyParser = require('koa-body-parser'),
router = require('koa-router'),
app = koa();
app.use(router(app));
app.use(bodyParser());
app.post('http://localhost/get',getit);

function *getit(){
 console.log(this.req.body); //undefined
}

and then send a post reqeust via jquery ajax :

 var xhr = $.ajax({
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json',
            url: 'http://localhost/getit',
            data: {"name":"me"},
            success: function(response) {

            }
        });

but in koa and in this.req i cant find my data. in google chrome developer tools i can see the header and everything send ok but i cant see it in koa.

Update

the correct is :

   function *getit(){
 console.log(this.request.body); //undefined
}
Was it helpful?

Solution

Interesting, I came across the same error, but my issue was the ordering of app.use() statements. The below does NOT work for me, and returns 'undefined' for this.request.body:

var koa = require('koa');
var router = require('koa-router');
var bodyParser = require('koa-body-parser');

var app = koa();
app.use(router(app));
app.use(bodyParser());

app.post('/login', function *() {
    this.response.body = this.request.body;
});

app.listen(3000);

However, if I reverse the order of the two app.use() statements to the following:

app.use(bodyParser());
app.use(router(app));

I can then see the elements in this.request.body. I'm using koa v0.5.5, koa-body-parser v1.0.0, koa-router v3.1.2, and node v0.11.12.

OTHER TIPS

I would use the co-body module instead (the same module used internally by koa-body-parser). The code should looks like:

var koa = require('koa');
var _ = require('koa-route');
var parse = require('co-body');

var app = koa();

app.use(function* (next) {
  this.req.body = yield parse(this);
  yield next;
});

app.use(_.post('/login', function* () {
    this.body = this.req.body;
}));

app.listen(3000);

The var body = yield parse(this); line does the trick, the parse method will try to parse any request but you can replace it with parse.json, parse.form or parse.text in case you need more control

koa uses middleware in the order you initialized them. so if you insert the router before the bodyparser it will not work. since your request wont pass to the parser before it gets to the router middleware, the request wont be parsed and koa will ignore the request.body. so the ordering is really important.

Solution

Acording to comment , the correct for me is this.request.body and this.req.body is not correct.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top