1. 程式人生 > >前後端分離跨域解決方案(反向代理)

前後端分離跨域解決方案(反向代理)

前後端分離是大趨勢,今天就前後端分離中出現的跨域參考各大博文,實現下通過伺服器反向代理解決跨域問題的一個例子,小小的賣弄一下。大神勿噴,請多指教!!

先說下思路吧,開發中碰到的跨域提示是這樣的

XMLHttpRequest cannot load http://www.test1.com/jqWebPrj/getCountAndTotalMil?driverNo=37.
No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'http://www.test2.com' is
therefore not allowed access.
vue.$http.get(' http://www.test1.com/getCountAndTotalMil?driverNo=37')
                .then((response) => {
                    var count = response.data;
                    vue.items.push(count);
                }, (response) => {
                    console.dir(response);
                })
;

出現如上提示是由於我在 www.test2.com 的專案上通過Ajax請求 www.test1.com上的資源,提示資源無法訪問。

www.test1.com是後臺程式伺服器。
www.test2.com是前端專案伺服器。

解決思路是
讓前段通過訪問test2的網址能夠訪問到test1的資源,說的有點不明白。。。

  1. 在test2規定訪問後臺RUI特定格式例如 www.test2.com/api/……
  2. 前臺伺服器通過配置nginx把有 api 標記的資源請求轉發到www.test1.com 伺服器上

這樣前端依舊訪問自己的網址請求資源就不會出現跨域的問題。

nginx配置如下

把 www.test2.com 的請求中帶有 /api 的資源轉發到 www.test1.com 上,其他請求不轉發依舊訪問自己的資源


    server {
        listen       80;
        server_name  www.test2.com;
        #charset koi8-r;
        #access_log  logs/host.access.log  main;
        location / {
            root   html;
            index  index.html index.htm;
            #client_max_body_size    1000m; 
        }
        location /api/ {
            proxy_pass   http://www.test1.com/;  
            #client_max_body_size    1000m; 
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }

Ajax改成這樣

vue.$http.get(' http://www.test2.com/api/getCountAndTotalMil?driverNo=37')
                .then((response) => {
                    var count = response.data;
                    vue.items.push(count);
                }, (response) => {
                    console.dir(response);
                });