关于cookie乱码问题
小弟自学编程,写了一个登陆demo。发现cookie存入中文,网页端取出时乱码,网上找了半天也没解决。 服务器端代码 UserModels.getUserByTP(tel,password,function (err,user) { if(user.length>0){ req.session.user=user; var username = user[0].username; res.cookie(‘name’,username); console.log(encodeURI(username));//控制台也会出现乱码 res.render(‘sign/index’,{login_success:“登陆成功”}); } }); js取cookie代码
$(function () {
(function changeUserName() {
var name = getCookie('name');
$('.username').text(name);
console.log(name);
})();
function getCookie(cookie_name) {
var allcookies = document.cookie;
console.log(allcookies);
var cookie_pos = allcookies.indexOf(cookie_name);
console.log(cookie_pos);
if (cookie_pos != -1)
{
// 把cookie_pos放在值的开始,只要给值加1即可。
cookie_pos += cookie_name.length + 1;
console.log(cookie_pos);
var cookie_end = allcookies.indexOf(";", cookie_pos);
console.log(cookie_end);
if (cookie_end == -1) {
cookie_end = allcookies.length;
}
var value = unescape(allcookies.substring(cookie_pos, cookie_end));
}
return value;
}
1 回复
cookie存入的时候要进行url encode