前端: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
