前面看了很多的博客,在使用nginx進行反向代理的時候,都是講通過 build 后...但是,我只是希望在 npm run dev 的時候進行 nginx 的反向代理,因為我只是在開發環境啊!!! build 個錘子...
前提:后端環境已經搭建完成、前端頁面可通過npm進行啟動、下載好nginx
前端頁面接口:8081(這個端口可以通過配置文件自定義)

服務端接口:8902

nginx 包

大體思路:
1.nginx 上配置好監聽的端口號(這樣前端頁面訪問端口就能被檢測到)、代理到服務端的地址;
2.前端頁面配置文件,配置代理到 nginx 監聽端口;
3.啟動nginx(可以打開任務管理器,檢查nginx是否啟動,避免配置文件寫錯);
一.配置前端項目文件 config/index.js
需要注意是 dev 對象下面的相關屬性.....
module.exports = {
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/api':{//配置代理地址,前端請求的所有接口都需要帶的前綴
target:'http://localhost:80',
changeOrigin:true,//是否進行跨域
secure: false,
pathRewrite:{//我使用了 nginx 作為反向代理,所以,需要把前綴替換為nginx 配置中的代理路徑
'^/api':'/e',//服務器請求地址中,若沒有/api ,則替換為 /
}
}
},
// Various Dev Server settings
host: 'localhost', // can be overwritten by process.env.HOST
port: 8081, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
autoOpenBrowser: false,
errorOverlay: true,
notifyOnErrors: true,
poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
/**
* Source Maps
*/
// https://webpack.js.org/configuration/devtool/#development
devtool: 'cheap-module-eval-source-map',
// If you have problems debugging vue-files in devtools,
// set this to false - it *may* help
// https://vue-loader.vuejs.org/en/options.html#cachebusting
cacheBusting: true,
cssSourceMap: true
},
.......
.......
}
二.配置 nginx 包下面的 conf/nginx.conf
worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; #前端頁面服務器 server { #監聽端口和域名 listen 80; server_name localhost; #添加頭部信息 proxy_set_header Cookie $http_cookie; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Server $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; #添加攔截路徑和代理地址 location /e/ { proxy_pass http://localhost:8902/; #注意:使用代理地址時末尾記得加上斜杠"/"。 } } }
三.配置完成,測試訪問
未啟動nginx:

啟動nginx:請求完成,並查詢到了數據

Over....
