cookie跨域携带

6,911 阅读1分钟

前提:http://192.168.1.3:8013和http://192.168.1.3:8012为静态服务

http://192.168.1.3:3000后台服务

方法一:

通过配置ajax请求头'withCredentials'为true,以及后台配置('Access-Control-Allow-Origin','IP端口')和('Access-Control-Allow-Credentials',true),注意:Access-Control-Allow-Origin不能配置为‘*’;

代码实例:

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为例)

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的跨域携带,以及解决跨域请求

代码实例:

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。