cookie跨域攜帶

前提: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。

文章中如有理解錯誤的地方,歡迎你們批評。

相關文章
相關標籤/搜索