koajs / koa

Expressive middleware for node.js using ES2017 async functions

Home Page:https://koajs.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

ctx.message assignment of Chinese or Other language(such as Japanese) will throw an error: TypeError [ERR_INVALID_CHAR]: Invalid character in statusMessage

ShiliangLuo opened this issue · comments

I want to assign ctx.message to specific message, but koa throw an error. See: https://codesandbox.io/s/quiet-thunder-q7po0?file=/src/index.js

If I change the order of the sentence:

ctx.message = '中文';
ctx.body = 'hello world';

the program will run successfully, but the result of ctx.message is not changed. Puzzled!

commented

maybe you can avoid this error by this way:
ctx.message = new Buffer("中文").toString("base64");

ctx.body = { code: 0, data: ctx.body, msg: Buffer(ctx.message, "base64").toString() };

Japanese is also no error
See: link

THX, I'll try. But, what's the reason?

@ShiliangLuo 这似乎是node的问题,

执行ctx.message = '中文'; 时会设置 res.statusMessage = '中文';

对应代码在

koa/lib/response.js

Lines 111 to 115 in 8c1dd48

set message (msg) {
this.res.statusMessage = msg
},

node中对statusMessage做了限制,需要满足正则表达式/[^\t\x20-\x7e\x80-\xff]/,代码在

https://github.com/nodejs/node/blob/ccb8aae3932c13f33622203b2ffc5a33120e9d40/lib/_http_common.js#L224-L235

下面这个issue有提到这个问题
nodejs/node#28797

@ShiliangLuo 这似乎是node的问题,

执行ctx.message = '中文'; 时会设置 res.statusMessage = '中文';

对应代码在

koa/lib/response.js

Lines 111 to 115 in 8c1dd48

set message (msg) {
this.res.statusMessage = msg
},

node中对statusMessage做了限制,需要满足正则表达式/[^\t\x20-\x7e\x80-\xff]/,代码在

https://github.com/nodejs/node/blob/ccb8aae3932c13f33622203b2ffc5a33120e9d40/lib/_http_common.js#L224-L235

下面这个issue有提到这个问题 nodejs/node#28797

嗯,后来我找到原因了

Unfortunately this has little to do with Koa as Koa delegates status message assignment to node:http.res.statusMessage.