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.<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


问题链接如下:
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编码的字符串
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值