vue 使用axios 出现跨域请求的两种解决方法

mac2022-06-30  85

最近在使用vue axios发送请求,结果出现跨域问题,网上查了好多,发现有好几种结局方案。 1:服务器端设置跨域 header(“Access-Control-Allow-Origin:*”); header(“Access-Control-Allow-Headers:content-type”); header(“Access-Control-Request-Method:GET,POST”);

2:可以自己设置一个代理服务器,使用proxyTable 我比较推荐这种方法。 首先在config/index.js 里面找到proxyTable :{} ,然后在里面加入

"/api":{ target: 'http://47.104.218.122:8087', changeOrigin: true, pathRewrite: { '^/api': '/' } }

注意这里面 /api是你自定义的,写成什么都可以。target 设置你调用的接口域名和端口号。这里理解成用‘^/api’代替target里面的地址,后面组件中我们调接口时直接用api代替 。比如我要调用’http://47.104.218.122:8087/dictionaryType‘,直接写‘/api/dictionaryType’即可。 然后我们可以在main.js设置一个基础路径,这样你调用接口的时候可以不写api,直接写/接口名称即可。在main.js 设置 axios.defaults.baseURL = ”/api”; 然后掉接口的时候可以直接写let  _url4 = ”/dictionaryTypes”;这样就比较省事。

this.$axios.get(_url4) .then(response=>{ alert(response); alert(1); }) .catch(error=>{ console.log(error); })

 

转载于:https://www.cnblogs.com/ysx215/p/11446531.html

相关资源:JAVA上百实例源码以及开源项目
最新回复(0)