第一次学vue,自己摸索了好久。用axios的时候遇到了几个问题。跨域,还有就是多个proxyTable配置的时候出现的问题。记下,方便以后查阅
var _this=this;
_this.$axios.get("http://xxxx/js/shopData.json").then(res=>{
console.log(res.data)
})
这样写乍一看是没有问题的,但是浏览器抛出了一个错误
No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
什么意思呢?就是跨域了,那么应该怎么来解决这个跨域的问题?
1.首先在main.js配置如下代码
Vue.prototype.$axios = Axios
Axios.defaults.baseURL = '/api'
Axios.defaults.headers.post['Content-Type'] = 'application/json';
2.其次在index.js 中的proxyTable配置如下代码
proxyTable: {
'/api':{
target: "http://xxxx/",
secure: false,
changeOrigin:true,
pathRewrite:{
'^/api':''
}
}
},
然后把axios改成
var _this=this;
_this.$axios.get("/js/shopData.json").then(res=>{
console.log(res.data)
})
假设接口服务器在 https://xxxx,本地服务器是 http://localhost:8080
原接口 https://xxxx/js/shopData.json 代理到 http://localhost:8080/api/js/shopData.json
撒花,跨域成功~~~
如果我们有多个接口呢?webpack devserver proxy 如何匹配代理多个路径到不同host?
1.首先在index.js 中的proxyTable配置
proxyTable: {
'/api':{
target: "http://xxxx/",
secure: false,
changeOrigin:true,
pathRewrite:{
'^/api':''
}
},
'/test':{
target: "https://yyy/",
secure: false,
changeOrigin:true,
pathRewrite:{
'^/test':''
},
}
},
2.然后请求第二个接口就可以了,第二个接口为 https://yyy/order.php
var _this=this;
_this.$axios.get("/test/order.php").then(res=>{
console.log(res.data)
})
问题来了,报错
http://localhost:8080/api/test/order.php 403 (Forbidden)
找不到这个东西,为啥有带了api,难道自动匹配到第一个接口,在第一个接口找不到php这个文件才报错??
细想了一下会不会axios的配置默认带了api回头一看
3.更改axios的配置
Vue.prototype.$axios = Axios
Axios.defaults.baseURL = '/'
Axios.defaults.headers.post['Content-Type'] = 'application/json';
然后第一个接口url自己带上api就可以访问了/api/js/shopData.json
这个是我在开发中遇到的问题,希望能够帮助到你