Koa: Koa always overwrite `Content-Type` for JSON responses

Created on 11 Jan 2018  路  7Comments  路  Source: koajs/koa

const Koa = require('koa');
const app = new Koa();
app.use(ctx => {
  ctx.set('Content-Type', 'application/vnd.myapi.v1+json');
  ctx.body = {message: 'hello'};
});
app.listen(3000);

When running this code I aways get Content-Type: application/json; charset=utf-8.

I can make it work if I write the header after setting the body. It only affects json responses. I'm not sure if that's a bug, but I couldn't find any information about that behavior in documentation.

bug help wanted version-patch

Most helpful comment

seems like a bug where it overwrites the content type when the content type is set and has +json in it.

All 7 comments

Yes, setting body is basically a switch statement, where the default case is to assume value is json, which removes content-type and sets it to application/json.

https://github.com/koajs/koa/blob/6baa41178d3930df399fb367dbc3d73890760e02/lib/response.js#L179-L181

I'm not sure about intent but this might be a feature.
It's an easy fix by just checking setType (as most/all other cases does), but it's a breaking fix as users may be relying on this behaviour.

seems like a bug where it overwrites the content type when the content type is set and has +json in it.

Check if body has value of type object, and if the header contains +json preserve the user given header.
Is this the desired implementation of fix for this bug?

Is there a merged fix for this? I'm making an API JSON API compliant but having to manually declare type for every response is a hassle.

what's issue that keep the PR not merged?

For reference, the PR in question is #1131

I'm just gonna note this here, for others to use, as I had a hard time finding a solution.

A temporary "fix" to this, is to set a stringified JSON body, instead of a json object. Then the header will not be overridden, as we'll hit this condition where the setType assertion is made.

ctx.body = JSON.stringify(data)
Was this page helpful?
0 / 5 - 0 ratings

Related issues

SteveCruise picture SteveCruise  路  3Comments

dounine picture dounine  路  4Comments

TheRav3n picture TheRav3n  路  3Comments

coodoo picture coodoo  路  4Comments

sibelius picture sibelius  路  3Comments