Search code examples
javascriptjqueryajaxnode.jskoa

Request Body is undefined in KOA


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
}

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.