1. 程式人生 > >nodejs 設定中文cookie無效

nodejs 設定中文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.<anonymous> (/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'時就會報上面錯誤。


Paste_Image.png

故解決方案:
把字串轉成base64即可

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

base64轉到字串

new Buffer(str, 'base64').toString();//str是base64編碼的字串