(1).什么是跨域
跨域:由于瀏覽器同源策略,凡是發送請求url的協議、域名、端口三者之間任意一個與當前頁面地址不同即為跨域。存在跨域的情況:
網絡協議不同,如http協議訪問https協議。
端口不同,如80端口訪問8080端口。
域名不同,如qianduanblog.com訪問baidu.com。
子域名不同,如abc.qianduanblog.com訪問def.qianduanblog.com。
域名和域名對應ip,如www.a.com訪問20.205.28.90.
下面是項目使用vue-cli腳手架搭建
使用http-proxy-middleware 代理解決跨域問題
例如請求的url:“http://f.apiplus.cn/bj11x5.json”
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、使用axios請求數據時直接使用“/api”:
getData () {
axios.get('/api/bj11x5.json', function (res) {
? console.log(res)
})
通過這中方法去解決跨域,打包部署時還按這種方法會出問題。解決方法如下:
let serverUrl = '/api/'? //本地調試時
// let serverUrl = 'http://f.apiplus.cn/'? //打包部署上線時