前后端分離,使用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/;# 代理接口地址
        }

 

3、測試

 

前端發送請求: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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM