Search code examples
javascriptnode.jshttpkoa

Request body is undefined for POST request in KOA


i am a beginner in nodejs. I am trying to create an HTTP server that uses koa framework for handling HTTP requests. Following is the code for my server.

app.use(function * (next){
    var ctx = this;

    var resource = url.parse(ctx.request.url, true, true).pathname;
    switch(resource) {
            case '/':
                    resource = config.app.root + '/dist/index.html';
                    ctx.type = mime.lookup(resource);
                    ctx.body = fs.readFileSync(resource, 'utf-8');
                    ctx.response.set('Access-Control-Allow-Origin', '*');
                    break;
            case '/fudge/contact':
                    console.log('============================');
                    console.log(ctx.request); // no body
                    console.log('============================');
                    console.log(ctx.req);     // no body
                    console.log('============================');
                    console.log(ctx.request.body) // is undefined
                    break;
            default:
                    resource = config.app.root + resource;
                    ctx.type = mime.lookup(resource);
                    ctx.body = fs.readFileSync(resource, 'utf-8');
                    ctx.response.set('Access-Control-Allow-Origin', '*');
                    break;
    }});

As mentioned in the case '/fudge/contact' the ctx.request.body is undefined. But, when I check for ctx.request or ctx.req, it shows content-length as 98(or something non-zero).

Following is the output that i get:

============================

{ 
method: 'POST',
  url: '/fudge/contact',
  header: 
   { host: 'localhost:9090',
     'user-agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:36.0) Gecko/20100101 Firefox/36.0',
     accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
     'accept-language': 'en-US,en;q=0.5',
     'accept-encoding': 'gzip, deflate',
     'content-type': 'text/plain; charset=UTF-8',
     referer: 'http://localhost:9090/',
     'content-length': '98',
     connection: 'keep-alive',
     pragma: 'no-cache',
     'cache-control': 'no-cache'}}
============================
{ _readableState: 
   { objectMode: false,
     highWaterMark: 16384,
     buffer: [],
     length: 0,
... more lines but no body.
============================
undefined

Following is the client code: I have used HttpClient library of aurelia framework.

        contactUs(){
            this.http.createRequest('/fudge/contact')
                    .asPost()
                    .withBaseUri('http://localhost:9090')
                    .withHeader('Content-Type','text/plain')
                    .withContent('{"heading":this.heading, "firstName":this.firstName, "lastName":this.lastName, "query":this.query}')
                    .send();
            alert(`Thank you, ${this.fullName}, your query has been successfully submitted`);

    }

The above code is javascript - ES7 and is valid as I am using transpilers like Babel. Point is that i am able to send POST request to server successfully, but there is no body in the request. Please suggest some solution.

Versions used: Node v0.12.0, Koa v0.19.1


Solution

  • Koa doesn't parse the request body by default, you need to add a middleware for body parsing, like koa-body for example:

    var app     = require('koa')(),
        router  = require('koa-router'),
        koaBody = require('koa-body');
    
    app.use(router());
    
    app.post('/users', koaBody(),
      function *(next) {
        console.log(this.request.body);
        // => POST body
        this.body = JSON.stringify(this.request.body);
      }
    );
    app.listen(3131)
    console.log('curl -i http://localhost:3131/ -d "name=test"');
    

    Koa's philosophy is to have as little as possible in the core framework, and let people compound their system by assembling specialized middlewares. From what I have seen, there are a few different packages for parsing the request's body, some are simpler and others have more features/options (e.g. koa-better-body). It's all about giving choices to the developer without creating a big monolith.

    While this approach may seem strange at first, I personally like it: it allows me to choose only the features I need without bloating the framework with options for every possible use case.