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
- fix: Set body to if and @likegun closes #1059 closes #998 — committed to docschina/koa by jonathanong 3 years ago
Below is my case:
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 = nullequals 204it 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 istrue). Coming up with a good config name was difficult (as naming often is) then I thought maybe one could registernullbody meaning no content on koa https://github.com/koajs/koa/blob/master/lib/response.js#L139