Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Response code auto set to 204 after being previously set to 200 with undefined or null body. #1464

Closed
austin-rausch opened this issue May 19, 2020 · 3 comments · Fixed by #1493

Comments

@austin-rausch
Copy link

austin-rausch commented May 19, 2020

Koa version 2.12.0

Running this snippet and sending a request will return a 204 response code despite the status code being explicitly set to 200, it does return a 200 if you reverse the two lines:

const koa = require('koa');
const app = new koa();
app.use(ctx => {
  ctx.status = 200;
  ctx.body = undefined;
});
app.listen(3000);

This contradicts the documentation and I believe it is caused by not checking for _explicitStatus on this line.

I'm happy to fix the issue by adding the check there, I just want to confirm this is un-intended behavior or if its a mistake in the documentation. As far as I can tell the HTTP spec doesn't specifically mandate that a body be included on a 200 response, only that a 204 MUST NOT include a message-body.

@ejose19
Copy link
Contributor

ejose19 commented May 23, 2020

Yes, there are some cases one wants to reply with "no body" for other status codes as well, that's why I submitted #1447 which is already on latest version (2.12.0)

To obtain the result you want use as this

// This must be always set first before status, since null | undefined 
// body automatically sets the status to 204
  ctx.body = null;
// Now we override the 204 status with the desired one
  ctx.status = 200; 

notice the server won't respond with "null" value, it will be no response like it does for 204

@austin-rausch
Copy link
Author

I can't say I agree with the behavior, if a response code is set explicitly, then a body is set after it shouldn't change the response code. Thats a strange side effect that I don't think many people will expect.

If I set a status code, I would expect that status code to be what is returned assuming it is valid for the body given.

If the response code and body are invalid together I would expect an error to be thrown.

At the very least this side effect needs documented correctly. Again, offering to do it just looking for some confirmation or consensus.

@miwnwski
Copy link
Member

miwnwski commented Jul 25, 2020

A docs PR for response.body= seems sane 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants