Search code examples
javascriptnode.jskoa

koa2 using koa-bodyparser with a simple GET


I'm trying to understand how to configure koa-bodyparser with a simple GET. The following returns exactly the same body, if I include the parser or not:

const Koa = require('koa');
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');

const app = new Koa();
const router = new Router();

app.use(bodyParser());

var users = [{
  id: 1,
  firstName: 'John',
  lastName: 'Doe'
}, {
  id: 2,
  firstName: 'Jane',
  lastName: 'Doe'
}];

router
    .get('/api', async (ctx, next) => {
    console.log('Getting users from /api');
    ctx.body = ctx.request.body = users;
});

app.use(router.routes());

app.listen(3000, () => console.log('Koa app listening on 3000'));

The documentation says to:

// the parsed body will store in ctx.request.body
// if nothing was parsed, body will be an empty object {}
ctx.body = ctx.request.body;

I'm not sure if I'm parsing correctly with:

ctx.body = ctx.request.body = users;

Solution

  • koa-bodyparser parses the request body, not the response body. In a GET request, you typically are not receiving a body with the request. To return a JSON body to the caller, all you need to do, as you noted is

    router
      .get('/api', async ctx => {
        console.log('Getting users from /api');
        ctx.body = users;
      });
    

    If you want to see the parsing in action, you'll need a PUT, POST, PATCH, etc.

    router
      .post('/api', async ctx => {
        console.log('creating user for /api');
        const user = ctx.request.body;
        // creation logic goes here
        // raw input can be accessed from ctx.request.rawBody
        ctx.status = 201;
      });
    

    You would need to pass valid JSON in the post request with Postman or curl like this:

    curl -X POST \
      http://localhost:3000/api \
      -H 'Content-Type: application/json' \
      -d '{
        "firstName": "Zaphod",
        "lastName": "Beeblebrox"
      }'
    

    You'll find that the ctx.request.body has a JSON value, while ctx.request.rawBody has a string value of '{"firstName":"Zaphod","lastName":"Beeblebrox"}'. What does this buy you? In this instance it saves you from having to call JSON.parse(ctx.request.body) to get valid JSON. koa-bodyparser is more than just that though, as it stats in the docs, it handles JSON, Form, and Text bodies based on the Content-Type header passed with the request.