vue專案打包後請求地址錯誤/打包後跨域操作
阿新 • • 發佈:2020-11-04
vue專案 npm run dev時跨域請求正常,但是打包後請求地址就錯誤(請求地址不存在),請求不到資料。
在vue專案中常用的是proxyTable代理跨域,這個用起來比較方便,但是當專案打包後就遇到這個問題了。
解決辦法如下:
開啟config資料夾下的index.js檔案,新增以下程式碼
pathRewrite: { '^api':'https://*****.com' //填寫需要跨域的地址 }
2.配置開發環境地址,就是config資料夾下的dev.env.js檔案,新增以下程式碼:
'use strict' const merge = require('webpack-merge') const prodEnv = require('./prod.env') module.exports = merge(prodEnv,{ NODE_ENV: '"development"',API_HOST:'"/api"' //配置代理路徑的符號 })
3.配置生產環境地址,就是config資料夾下的prod.env.js檔案,新增以下程式碼:
'use strict' module.exports = { NODE_ENV: '"production"',API_HOST:'"https://**********.com/api"' //生產環境的地址 } })
如果介面地址沒有api這個公共路徑就不要添上了。
4. 接下來就該在元件中使用了。
methods : { getData() { let _this = this; this.http(this,{ //process.env.API_HOST 獲取當前環境的api地址 url : process.env.API_HOST+'/platform/index/new',// headersType : 1 //token }).then(res=>{ this.ShowSkeleTon = true; this.list = res.list; },err=>{ console.log(err); }); },},
然後就是修改所有元件中的url地址了
雖然比較麻煩,但可以完美解決這個問題。這樣即使打包後也可以請求到資料了。
補充知識:vue專案部署後跨域請求後端失敗(已解決)
未解決前
驗證碼載入失敗
解決後
驗證碼載入成功
解決辦法
在 nginx/conf/nginx.conf 下做如下配置
server { listen 8080; # 監聽的埠號 server_name 127.0.0.1; # 伺服器的ip地址 root /usr/local/nginx/html; # 伺服器中專案所在資料夾 #charset koi8-r; #access_log logs/host.access.log main; location / { # root /usr/local/nginx/html/; try_files $uri $uri/ /index.html; index index.html index.htm; } # 解決跨域請求 location /req { rewrite ^.+req/?(.*)$ /$1 break; proxy_pass http://127.0.0.1; #第一個跨域請求的地址 proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } # 解決跨域請求 location /api { proxy_pass http://127.0.0.1:/login; # 第二個跨域請求的地址 proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection ‘upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } }
注意:以上提供了兩種解決方法,但是當兩個都使用第二中方法時會出現問題。
以上這篇vue專案打包後請求地址錯誤/打包後跨域操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。