nodejs(koajs)設(shè)置中文cookie無(wú)效

通過(guò)koajs的cookies方法設(shè)置cookie時(shí),寫了中文的cookie值,一直失敗。代碼如下:

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

報(bào)錯(cuò)如下:

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)

倒騰了半夜也沒(méi)找到方案,其實(shí)是http協(xié)議的Header頭有字符限制,下圖是stackoverflow的解答,http的header字符集支持US-ASCII子集的字符集,故設(shè)置中文是'utf8'時(shí)就會(huì)報(bào)上面錯(cuò)誤。

Paste_Image.png

問(wèn)題鏈接如下:
http://stackoverflow.com/questions/4400678/http-header-should-use-what-character-encoding

故解決方案:
把字符串轉(zhuǎn)成base64即可

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

base64轉(zhuǎn)到字符串

new Buffer(str, 'base64').toString();//str是base64編碼的字符串
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容