前后端分離,使用nginx解決跨域問題
后臺: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
內容擴展思考:
1).
# 代理服務端接口
location?/api/?{ proxy_pass?http://localhost:8080/;#?代理接口地址 }
代理接口地址只到8080,那么他會自動將后臺項目的名稱加上??? 比如接口是http://148.70.110.87:8080/項目名稱/方法名稱 。。。
2).js 中是這樣請求的 ,nginx是按照您上面的配置,但是請求出錯http://148.70.110.87/api/index2 404 (not found)
axios.post('/api/index2') .then(?(response)?=>{ console.log(response); }) .catch(?(error)=>?{ console.log(error); });
3).第三個步驟,測試,實在看不懂要是能有相關的代碼就好了
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END