产生原因:
Safari will not set cookies with non-ASCII characters in their value and other browsers can be unpredictable in how they display non-ASCII characters. As semi-colon is also not allowed in cookie values for any browser I would recommend using UrlEncode/UrlDecode.
即safari在进行cookie 编码时使用的ASCII编码,中文字符是不被认可的字符,需要使用UrlEncode和UrlDecode进行编码和解码
解决方法:
在网上搜索了解决方案,分为前端解决和服务端解决,我使用了前端的解决方案
在编码时使用encodeURIComponent()方法对name的值进行编码
如下:
document.cookie = 'name=' + encodeURIComponent(response.data.name) + ';expires=' + exp.toGMTString()
在获取值时使用decodeURI进行解码:
getCookieName () {
let name = 'name='
let ca = document.cookie.split(';')
for (var i = 0; i < ca.length; i++) {
var c = ca[i].trim()
if (c.indexOf(name) === 0) return decodeURI(c.substring(name.length, c.length))
}
return ''
}
网友评论