前后端分離,使用nginx解決跨域問題
后臺:SpringBoot
反向代理服務(wù)器:nginx
思想:將前端代碼打包,讓nginx指向靜態(tài)資源,nginx對后臺請求進(jìn)行轉(zhuǎn)發(fā)。
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; } } # 代理服務(wù)端接口 location /api/ { proxy_pass http://localhost:8080/;# 代理接口地址 }
測試
前端發(fā)送請求:http://localhost/test ,vue-router將其重定向為http://localhost/api/demo/1,實際訪問是http://localhost:8080/demo/1。
直接向后臺發(fā)送請求:訪問http://localhost/api/demo/1,實際訪問是:http://localhost:8080/demo/1
更多Nginx相關(guān)技術(shù)文章,請訪問Nginx使用教程欄目進(jìn)行學(xué)習(xí)!?
? 版權(quán)聲明
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載。
THE END