當我們前端要調用跨域接口時,我們需要用代理解決跨域問題,比如Vue的代理配置proxy,但是當Vue項目打包成靜態文件時,他的代理也就失靈了,因爲代理的前提是本地必須有service,本章講一下生產環境的Vue項目如何做代理。
本章我們從兩方面講解Vue解決跨域的方案,一種是本地開發環境,另一種是生產環境(nginx解決vue跨域問題)
1.Vue本地(開發環境)解決跨域流程如下
(1)打開config/index.js,在proxyTable中添寫如下代碼:
proxyTable: {
'/api': { //使用"/api"來代替"http://f.apiplus.c"
target: 'http://f.apiplus.cn', //源地址
changeOrigin: true, //改變源
pathRewrite: {
'^/api': 'http://f.apiplus.cn' //路徑重寫
}
}
}
(2)請求接口時加上‘/api’前綴
getData () {
axios.get('/api/bj11x5.json', function (res) {
console.log(res)
})
2.生產環境解決跨域問題流程如下
(1)打包
我們通過win+R命令打開CMD窗口,找到我們項目根目錄 運行 npm run build命令
(2)服務器安裝nginx服務器
安裝步驟 https://www.cnblogs.com/AlanLee/p/9044644.html
(3)配置nginx
找到nginx的配置文件 nginx.conf ,它的路徑是 /etc/nginx/nginx.conf
nginx.conf的配置如下
server {
listen 8000;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location /api {
proxy_pass https://www.baidu.com; #代理的域名
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
}
location / {
root /var/www/vue/;
index index.html index.htm;
}
}
解釋如下:
https://www.baidu.com 是我們要代理域名
add_header 是增加返回頭 解決跨域問題
注意:vue項目在請求域名的前面就要加上“/api”字符串,請求示例如下
test.post('/api/product/getData',params)