vue工程 npm run build 后把dist包放到 nginx代理服務器的html目錄,在conf/nginx.conf配置文件中增加配置,這樣就可以正常方位后端接口了,配置如下:
server {listen 8193;server_name localhost 127.0.0.1;location / {root D:\agent\html;index index.html index.htm;}
}
vue工程中 配置后端IP地址如下:
const instance = axios.create({baseURL: process.env.NODE_ENV === 'development' ? '/api' : '192.168.1.128:8185',timeout: 10000,headers: {'Content-Type': 'application/json;charset=UTF-8'}
})
在瀏覽器中輸入? localhost:8193? 打開前端網頁,但出現了后端接口請求跨域問題。原因是localhost:8193? 和發送的后端請求192.168.1.128:8185 IP 和 端口都不同,所以出現了跨域。
我們在nginx上配置轉發就可以解決此跨域問題,修改步驟如下:
1. 在nginx代理服務器配置文件中配置上轉發,配置如下:
server {listen 8193;server_name localhost 127.0.0.1;location / {root D:\agent\html;index index.html index.htm;}location /file/get {proxy_pass 192.168.1.128:8151;}
}
發送后端接口/file/get 會被轉發到后端192.168.1.128:8151
2. 修改vue工程中的后端接口地址 和 打開前端頁面的地址相同,如下所示:
const instance = axios.create({baseURL: process.env.NODE_ENV === 'development' ? '/api' : 'localhost:8193',timeout: 10000,headers: {'Content-Type': 'application/json;charset=UTF-8'}
})
這樣打開前端網頁的地址和請求后端接口的地址相同,瀏覽器就不會報跨域請求錯誤了。而接口通過nginx 又被轉發到正確的后端接口地址,所以接口就能正常訪問了。