1. 程式人生 > >NGINX解決AJAX呼叫跨域的問題完整實現

NGINX解決AJAX呼叫跨域的問題完整實現

這兩天一直在研究ajax呼叫跨域的問題處理,使用了多種方法都無法解決,網上看了很多列子要麼不全要麼不符合要求,要麼實驗後無法調通,比如使用jsonp(只支援get請求),但是我們系統必須要用post請求,在後臺加允許跨域('Access-Control-Allow-Origin' '*';)也是不行,因為需要經過閘道器轉發到後臺,閘道器不允許設定跨域,候來考慮用nginx或者zuul,nginx和zuul都可以實現nginx相對來說比較麻煩些,zuul加入pom.xml的依賴和加app.properties的配置就行,下面我們來詳細說明下實現過程,以做記錄後續參考。

1,請求呼叫的ajax方法,post的data引數需要用JSON.stringify格式化,不然請求傳送過去的data是無法識別

function loginOauth(){
    var dataValue= [{
        'client_id':'xxxxxxxxxxxxxxxxxxx',
        'response_type':'code',
        'redirect_uri':'http://xx.xxx.com:8181/html/index.html'
    }];
    // alert(JSON.stringify(dataValue));
    $.ajax({
        type: 'POST',
        timeout: 30000, // 超時時間 10 秒
        contentType: 'application/json',
        headers: {
            'CallerModule' : 'xxx',
            'CallerModuleVersion' : '1.0.0',
            'Content-Type':'application/json'
        },
        url: 'http://10.200.47.231:8287/OAuth2/authorize',
        data: JSON.stringify(dataValue) ,
        success: function(data) {
            alert(data);
            $(location).attr('href', data);
        },
        error: function(err) {
            console.log(err);
        },
        complete: function(XMLHttpRequest,status) { //請求完成後最終執行引數 
            // alert(JSON.stringify(XMLHttpRequest));
            var ajaxobj=eval("("+JSON.stringify(XMLHttpRequest)+")");
            console.log('data='+ajaxobj.responseText);
            var dataobj=eval("("+ajaxobj.responseText+")");
            console.log('data='+dataobj.data);
            // alert(status);
            $(location).attr('href', dataobj.data);
        }
    });

}

2,nginx的配置如下,windows啟動nginx到nginx的安裝目錄執行start nginx,停止執行nginx.exe -s quit   

server {
        listen       8287;    # nginx的埠扣
        #access_log  logs/host.access.log  main;
        add_header Access-Control-Allow-Origin *;  # 允許跨域
        location / {                          #nginx的過濾路徑
           if ($request_method = 'OPTIONS') {
                add_header 'Access-Control-Allow-Origin' '*';   # 允許跨域的鬱悶
                add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
                add_header 'Access-Control-Allow-Headers' '*';  # 允許設定的請求頭
                add_header 'Access-Control-Max-Age' 1728000;
                add_header 'Content-Type' 'text/plain charset=UTF-8';
                add_header 'Content-Length' 0;
                return 204;
            }
            if ($request_method = 'POST') {
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
            add_header 'Access-Control-Allow-Headers' '*'; 
            add_header 'Access-Control-Expose-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
            }    
            proxy_pass https://xx-di1.xx.xx.com/;   #需要請求的目標伺服器地址
        }
    
    }