首頁  >  文章  >  運維  >  nginx怎麼解決跨域

nginx怎麼解決跨域

(*-*)浩
(*-*)浩原創
2019-07-13 15:15:064101瀏覽

前後端分離,使用nginx解決跨域問題

nginx怎麼解決跨域

#前端:vue.js nodejs webpack

後台:SpringBoot

反向代理伺服器:nginx

想法:將前端程式碼打包,讓nginx指向靜態資源,nginx對後台請求進行轉送。

1、將前端程式碼打包:

npm run build

會產生一個dist資料夾。包含一個index.html檔案和一個static資料夾,路徑以我本機為例:

/Users/xxx/ideaProjects/webtest/dist

2、開啟

################################################################################ /usr/local/etc/nginx目錄下的nginx.conf,在server中加入如下: ###
listen       80; #原为8080,避免冲突,更改为80
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;


        location / {
            root   /Users/xxx/ideaProjects/webtest/dist;
            index  index.html;
            
            # 此处用于处理 Vue、Angular、React 使用H5 的 History时 重写的问题
            if (!-e $request_filename) {
                rewrite ^(.*) /index.html last;
                break;
            }
        }


        # 代理服务端接口
        location /api/ {
            proxy_pass http://localhost:8080/;# 代理接口地址
        }
######測試#########前端發送請求:http://localhost /test ,vue-router將其重定向為http://localhost/api/demo/1,實際存取是http://localhost:8080/demo/1。 ######直接向後台發送請求:訪問http://localhost/api/demo/1,實際訪問是:http://localhost:8080/demo/1######更多Nginx相關技術文章,請造訪###Nginx使用教學###欄位進行學習! ###

以上是nginx怎麼解決跨域的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn