So far, we’ve only used strings as bodies.
Koa supports the following types of bodies:

  • Strings
  • Buffers
  • Streams (node)
  • JSON Objects

If the body is not treated as the first three,
Koa will assume that you want to send a JSON response,
treating REST APIs as first-class citizens.

  1. app.use(function* (next) {
  2. this.response.body = {
  3. message: 'this will be sent as a JSON response!'
  4. };
  5. })

When setting a stream as a body,
Koa will automatically add any error handlers so you don’t have to worry about error handling.

  1. var fs = require('fs');
  2. app.use(function* (next) {
  3. this.response.body = fs.createReadStream('some_file.txt');
  4. // koa will automatically handle errors and leaks
  5. })

Exercise

Create an app that returns a stream when the client requests /stream and a JSON body when the client requests /json.

Bonus

When setting the body of the stream, Koa can’t infer the Content-Length of the
body. Set the Content-Length header yourself using this.response.length=
and the “yieldable” version of fs you’ve created in exercise 1.