接上一篇
在开发h5+手机app时,服务器写到客户端的cookie却无法正常获取
一、错误方法
1、后端设置cookie(用来设置会员15天免登陆)
Cookie phone = new Cookie("phone", menber.getPhone());
Cookie password = new Cookie("password", menber.getPassword());
phone.setMaxAge(15 * 24 * 3600);//15天
phone.setPath("/");
password.setMaxAge(15 * 24 * 3600);
password.setPath("/");
response.addHeader("Access-Control-Allow-Credentials", "true");
response.addCookie(phone);
response.addCookie(password);
2、前端获取cookie
$.ajax({
...
dataType: "jsonp", //数据格式设置为jsonp
jsonp: "callback", //Jquery生成验证参数的名称
xhrFields: {
withCredentials: true
},
crossDomain: true,
success:function(){
console.log(document.cookie)
},
...
})
控制台输出一直是null,获取失败。。。
失败原因:尽管ajax请求已经设置跨域了,但是js原生的cookie本身就不支持跨域,更何谈接受后端发送过来的跨域cookie。
解决办法:考虑到本项目是h5+app,所以查看h5+规范以及我上一片博客可以知道,plus.navigator.getCookie(url)可以取代原生cookie,因为他可以跨域,从而正常获取后端传过来的cookie,当然,代码也有变动
二、可行办法
Cookie phone = new Cookie("phone", menber.getPhone());
Cookie password = new Cookie("password", menber.getPassword());
phone.setMaxAge(15 * 24 * 3600);//15天
phone.setPath("/");
phone.setDomain("192.168.137.1");
password.setMaxAge(15 * 24 * 3600);
password.setPath("/");
password.setDomain("192.168.137.1");
response.addHeader("Access-Control-Allow-Credentials", "true");
response.addCookie(phone);
response.addCookie(password);
$.ajax({
...
jsonp: "callback", //Jquery生成验证参数的名称
xhrFields: {
withCredentials: true
},
crossDomain: true,
success: function(data) {
console.log(plus.navigator.getCookie("http://192.168.137.1:8080/"))
}
})