前提:http://192.168.1.3:8013和http://192.168.1.3:8012为静态服务html
http://192.168.1.3:3000后台服务node
方法一:nginx
经过配置ajax请求头'withCredentials'为true,以及后台配置('Access-Control-Allow-Origin','IP端口')和('Access-Control-Allow-Credentials',true),注意:Access-Control-Allow-Origin不能配置为‘*’;ajax
代码实例:json
ajax代码:跨域
document.cookie = "sessinId3 = 1231234";
jsUtils.cors.execAjax({
method:'get',
async:true,
url:'http://192.168.1.3:3000/getJsonStr',
withCredentials: true,
reqType: 'application/json',
success:function (res) {
console.log(res);
},
error:function () {
console.log('XDR失败');
}
})
复制代码
后台代码(以nodejs为例)bash
app.get('/getJsonStr', (req, res)=> {
res.header('Access-Control-Allow-Origin','http://192.168.1.3:8013');
res.header('Access-Control-Allow-Credentials',true);
res.send(testData);
});
复制代码
方法二:服务器
经过配置代理,利用服务器和服务器之间不存在跨域的特性,达到cookie的跨域携带,以及解决跨域请求cookie
代码实例:app
ajax代码:
document.cookie = "sessinId2 = 1231234";
jsUtils.cors.execAjax({
method:'get',
async:true,
url:'/getJsonStr',
success:function (res) {
console.log(res);
},
error:function () {
console.log('XDR失败');
}
})
复制代码
nginx服务配置代码
server {
listen 8012;
server_name 192.168.1.3;
location / {
root html2/;
index index.html index.htm;
}
location /getJsonStr {
rewrite ^/getJsonStr/(.*)$/$1 break;
proxy_pass http://192.168.1.3:3000;
}
}
复制代码
总结:方法一的cookie跨域携带须要在每个请求里加上withCredentials凭证,能够针对性的针对某一个ajax请求去配置是否携带cookie,方法二的经过代理配置携带cookie会在我代理的每个请求都把cookie携带上。方法二方法一均可以灵活的配置去为某一个请求携带cookie,在项目中因为作单点登陆,须要整合7个厂家cookie信息,已达到每一次请求都刷新cookie时间,而且本着减小其余厂家工做量的缘由,故此采用了nginx服务配置的方式去携带cookie。
文章中如有理解错误的地方,欢迎你们批评。