koa: Empty response if result is null

Why the following returns an empty response? null is a valid json value.

const config = require('./package.json');

const http = require('http');
const koa = require('koa');
const cors = require('kcors');
const compress = require('koa-compress')
const noTrailingSlash = require('koa-no-trailing-slash');
const json = require('koa-json');
const body = require('koa-body');
const send = require('koa-send');
const router = require('koa-router')();

const app = new koa();

app.use(cors());
app.use(compress());
app.use(noTrailingSlash());
app.use(json({ pretty: true, spaces: 4 }));
app.use(body({ formLimit: '5mb', jsonLimit: '5mb', strict: false, multipart: true }));

app.use(async (ctx, next) => {
    try {
        await next();
    }
    catch(error) {
        ctx.status = 400;
        ctx.body = error.message || error;
    }
});

router.all('/ciao', async ctx => {
    ctx.body = null;
});

app.use(router.routes());
http.createServer(app.callback()).listen(8080);

Reponse is empty:

macbook:react-app damiano$ curl -v localhost:8080/ciao
*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8080 (#0)
> GET /ciao HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.51.0
> Accept: */*
> 
< HTTP/1.1 204 No Content
< Vary: Origin, Accept-Encoding
< Date: Fri, 09 Jun 2017 14:17:57 GMT
< Connection: keep-alive
< 
* Curl_http_done: called premature == 0
* Connection #0 to host localhost left intact
macbook:react-app damiano$ 

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 6
  • Comments: 20 (6 by maintainers)

Commits related to this issue

Most upvoted comments

Below is my case:

request(options, function(error, response, body){
    //...
    ctx.status = response.statusCode; //500
    ctx.body = body; //undefined
    console.log(ctx.status); //204, it confused me
    //...
});

if ctx.body == null and ctx.status is 2XX or not set, we can set ctx.status to 204, otherwise it’s better do nothing.

@maapteh after 4 years I gave up and came up with a https://www.npmjs.com/package/koa-better-json

OK , If ctx.body = null equals 204

middleware: 

( async (ctx) => {

ctx.body = null;
ctx.body = 'have result'
return ctx;

})

it still return 204 , anyone have this issue ?

I’m willing to provide a PR. I saw this in the 3.0 roadmap initial issue #1114 as a breaking change. Instead of breaking the current behaviour I’d suggest that to be a config option one can set when creating the koa app. That way it would not break old clients and clients that need it can enabled it via emptyBodyAs204=false (default is true). Coming up with a good config name was difficult (as naming often is) then I thought maybe one could register