jquery + node 經過 CORS 實現跨域訪問,支持cookie和自定義header

  跨域有多種方式,如今的狀況看來仍是CORS更適合一些,有不少優勢,好比瀏覽器正式支持、支持post、能夠控制跨域訪問的網站等。html

 

  咱們來看看node如何實現cors方式的跨域。在網上找到了一些代碼,考過來以後運行報錯,可能這個是在express裏面的寫法吧,那麼原生的寫法是什麼樣子的呢?又找了半天,而且通過測試獲得了原生的寫法:node

 

express的寫法:ajax

---app.js---
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1')
    if(req.method=="OPTIONS") res.send(200);/*讓options請求快速返回*/
    else  next();
});

 

node原生寫法:express

var http = require("http");

http.createServer(function (req, res) {

     
        var a={
            "a1":"www"
        };

        // 得到客戶端的Cookie
        var Cookies = {};
        req.headers.cookie && req.headers.cookie.split(';').forEach(function( Cookie ) {
            var parts = Cookie.split('=');
            Cookies[ parts[ 0 ].trim() ] = ( parts[ 1 ] || '' ).trim();
        });
        console.log(Cookies);

        //獲取自定義頭
        console.log(req.headers.xtoken);

        // 向客戶端設置一個Cookie
        res.setHeader('Set-Cookie','myCookie2=test');

        //res.setHeader("Access-Control-Allow-Origin", "*");
        res.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:8050"); //帶cookie的話,不能寫*
        res.setHeader("Access-Control-Allow-Credentials", true); //容許帶 cookie
        res.setHeader("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With,xToken");
        res.setHeader("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
        res.setHeader("X-Powered-By",' 3.2.1');
        res.writeHeader(200, {'Content-Type': 'application/json'});

        if(req.method=="OPTIONS"){
            /*讓options請求快速返回*/
            res.end();
        }
        else
        {
            res.write(JSON.stringify(a));
            res.end();
        }

    }

}).listen(8080);

 

 

  須要先用 setHeader 進行設置,最後再用 writeHeader 進行設置。這樣就能夠了。json

  還有一些小地方,設置很差的話很容易報錯。翻來覆去調試了很久纔好。後端

 

  而後就是客戶端的寫法了,因爲客戶端使用的框架不一樣,設置方式也有點差異,這裏先介紹一下比較基本的jQuery的方式。跨域

 

$.ajax({
               type: "POST",          //post方式 
               dataType: "JSON",      //json格式的數據
               cache: false,           //客戶端不緩存
               headers: {           //自定義頭
                   xtoken: "1234qwert"
               },
               xhrFields: {
                 //容許跨域訪問時添加cookie
                 withCredentials: true     //true "Access-Control-Allow-Origin" 不能寫* ;false能夠寫 *
               },
               crossDomain: true,
               url: "http://127.0.0.1:8080/1234",
               data: {"a":"11"},        //json格式的數據
               //timeout: 2000,
               error: function (request, textStatus, errorThrown) { //訪問失敗,自動中止加載動畫,而且給出提示
                   alert("提交的時候發生錯誤!");

               },

               success: function (data) {
                    $("#div").html(data.a1);

               }
           });

 

  這裏的 xhrFields 設置,折騰半天,找了很久終於搞定了。其實只須要在後端加一行代碼就行。瀏覽器

 

  另外用了自定義頭,客戶端會自動發起兩次請求。就是說你的代碼之ajax了一次,可是瀏覽器會發起兩個請求,後端會收到兩個請求,因此有了緩存

if(req.method=="OPTIONS") res.send(200); 這樣的判斷。

 

 

參考目錄cookie

 

一、node的原生 header: https://www.cnblogs.com/jay--zhang/p/6229139.html 

 

二、node 接收 自定義 header

 做者:zding92 
來源:CSDN 
原文:https://blog.csdn.net/u011481543/article/details/79582555 
 

 

三、解決cookie的問題 :https://www.jb51.net/article/137278.htm

相關文章
相關標籤/搜索