VUE axios 跨域问题-最完美的解决方法
VUE axios 跨域问题 No 'Access-Control-Allow-Origin' header is present on the requested resource.开发环境中,使用axios调用接口时,出现跨域的时候会被浏览器拦截,故而造成请求失败,并且在控制台中显示No 'Access-Control-Allow-Origin' header is...
VUE axios 跨域问题 No 'Access-Control-Allow-Origin' header is present on the requested resource.
开发环境中,使用axios调用接口时,出现跨域的时候会被浏览器拦截,故而造成请求失败,并且在控制台中显示No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8081' is therefore not allowed access.
跨域的解决办法有很多,不一一罗列,在此仅记录我自己的解决办法。
项目环境:
vue v2.5
vue-cli v2.9(3.0的版本改动很大,需要参考官方文档,在vue.config.js中进行对应的修改,若无此文件自行添加。)
webpack v3.6
解决办法:
项目根目录中找到config/index.js文件,找到 proxyTable 添加如下配置
proxyTable: {
'/gamutgameshow':{ // 要代理的接口名
target:'http://192.168.0.3:8080/gamutgameshow', // 要代理的接口地址
changeOrigin:true, // 允许跨域
pathRewrite:{'^/gamutgameshow':''} // 接口名重写
}
}
然后回到你的项目中需要发送接口请求的地方,修改请求的地址换成我们写好的代理接口名即可,'/gamutgameshow'
axios.get('/gamutgameshow').then(res=>{
console.log(res)
}).catch(err=>{
console.log(err)
})
运行结果:
这里我们跨域的问题就解决了。(至于没有返回200,请自行忽略 *^_^* )
注意:这里的代理只适用于开发环境,上线的项目要修改为正常的接口请求地址!!!
更多推荐
所有评论(0)