nodejs(koajs)设置中文cookie无效

通过koajs的cookies方法设置cookie时,写了中文的cookie值,一直失败。代码如下:

this.cookies.set('test', '我是koajs')

报错如下:

sent error argument value is invalid to the cloud
TypeError: argument value is invalid
    at new Cookie (/Users/zyy/github/fete/node_modules/cookies/lib/cookies.js:110:11)
    at Cookies.set (/Users/zyy/github/fete/node_modules/cookies/lib/cookies.js:73:16)
    at Object. (/Users/zyy/github/fete/app.js:54:18)
    at next (native)
    at onFulfilled (/Users/zyy/github/fete/node_modules/co/index.js:65:19)
    at /Users/zyy/github/fete/node_modules/co/index.js:54:5
    at Object.co (/Users/zyy/github/fete/node_modules/co/index.js:50:10)
    at converted (/Users/zyy/github/fete/node_modules/koa-convert/index.js:17:15)
    at dispatch (/Users/zyy/github/fete/node_modules/koa-compose/index.js:43:32)
    at next (/Users/zyy/github/fete/node_modules/koa-compose/index.js:44:18)
    at createGenerator (/Users/zyy/github/fete/node_modules/koa-convert/index.js:24:16)
    at next (native)
    at onFulfilled (/Users/zyy/github/fete/node_modules/co/index.js:65:19)
    at /Users/zyy/github/fete/node_modules/co/index.js:54:5
    at Object.co (/Users/zyy/github/fete/node_modules/co/index.js:50:10)
    at Object.toPromise (/Users/zyy/github/fete/node_modules/co/index.js:118:63)

倒腾了半夜也没找到方案,其实是http协议的Header头有字符限制,下图是stackoverflow的解答,http的header字符集支持US-ASCII子集的字符集,故设置中文是'utf8'时就会报上面错误。

nodejs(koajs)设置中文cookie无效_第1张图片
Paste_Image.png

问题链接如下:
http://stackoverflow.com/questions/4400678/http-header-should-use-what-character-encoding

故解决方案:
把字符串转成base64即可

this.cookies.set('test', new Buffer('我是koajs').toString('base64'))

base64转到字符串

new Buffer(str, 'base64').toString();//str是base64编码的字符串

你可能感兴趣的:(nodejs(koajs)设置中文cookie无效)