axios实现跨域三种方法_跨域的解决方案
生活随笔
收集整理的這篇文章主要介紹了
axios实现跨域三种方法_跨域的解决方案
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
問題背景
Axios是不允許跨域訪問的,別說跨域,跨端口都不行。例如某項目我本地vue前端frontEnd為localhost:8889,Java后臺 backEnd為localhost:8888
報錯信息: Access to XMLHttpRequest at 'http://localhost:8888/cert/certCompany/list2' from origin 'http://localhost:8889' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
axios請求代碼:
axios.post('http://localhost:8888/cert/certCompany/list2',JSON.stringify(this.searchParam))
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
這個時候就有兩個方案了:
- 修改
frontEnd前端,支持跨域(通過代理的形式,當然這種是偽跨域,但是挺有用,前提是后端不限制即可)。 - 修改
backEnd后臺,支持跨域(同時限制可跨域名,不在本文討論范圍,且看過往處理方式):
SpringBoot之跨域過濾器配置允許跨域訪問
SpringCloudApiGateway之支持Cors跨域請求
解決方案
main.js
引入axios
//引入axios by zhengkai.blog.csdn.net
import axios from 'axios'
Vue.prototype.$axios = axios
axios.defaults.baseURL = '/api' //自動附加在所有axios請求前面,則可以省略/api,直接寫'/xxxx/xxx'。否則需要設置'/api/xxxx/xxx'
config.index.js
改造proxyTable部分,引入虛擬代理 ,請求target這個地址的時候直接寫成/api即可。
dev: {
env: require('./dev.env'),
port: 8889,
autoOpenBrowser: true,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
//axios跨域改造 by zhengkai.blog.csdn.net
'/api': {
target:'http://localhost:8888/cert/', // 你請求的第三方接口
changeOrigin:true, // 在本地會創(chuàng)建一個虛擬服務端,然后發(fā)送請求的數(shù)據(jù),并同時接收請求的數(shù)據(jù),這樣服務端和服務端進行數(shù)據(jù)的交互就不會有跨域問題
pathRewrite:{
// 路徑重寫,
'^/api': '' // 替換target中的請求地址,也就是說/api=/target,請求target這個地址的時候直接寫成/api即可。
}
}
},
// CSS Sourcemaps off by default because relative paths are "buggy"
// with this option, according to the CSS-Loader README
// (https://github.com/webpack/css-loader#sourcemaps)
// In our experience, they generally work as expected,
// just be aware of this issue when enabling this option.
cssSourceMap: false
}
業(yè)務.vue
修改請求為/api封裝開頭(但是如果你的借口包含/api的關鍵字的話,建議使用其他關鍵字)
//axios跨域請求改造 by zhengkai.blog.csdn.net
axios.post('/certCompany/list2',JSON.stringify(this.searchParam))
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
驗證效果
請求不報錯,沒有煩人的No 'Access-Control-Allow-Origin' header is present on the requested resource.報錯。
總結
以上是生活随笔為你收集整理的axios实现跨域三种方法_跨域的解决方案的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: pagehelper,pageinfo用
- 下一篇: 【芜湖网站建设】SEO网站优化的6个重要