axios跨域接口
2019-10-30 本文已影响0人
回忆不死我们不散
方法1


方法2


方法3


config下的index.js
proxyTable: {
'/api': {
target: 'https://api.apiopen.top',//后端接口地址
changeOrigin: true,//是否允许跨越
pathRewrite: {
'^/api': '',//重写,
}
}
}
mounted(){
const url='/api'
this.$axios.get(url+'/videoRecommend?id=127398')
.then((res) => {
console.log(res) //返回的数据
})
.catch((err) => {
console.log(err) //错误信息
})
}
法4 完整的求情路径https://api.apiopen.top/videoRecommend?id=127398


mounted(){
const url = '/demo'
this.$axios.get(url+'/videoRecommend?id=127398')
.then((res) => {
console.log(res) //返回的数据
})
.catch((err) => {
console.log(err) //错误信息
})
}
proxyTable: {
'/demo': {
target: 'https://api.apiopen.top',//后端接口地址
changeOrigin: true,//是否允许跨越
pathRewrite: {
'^/demo': '',//重写,
}
}
},
方法1
我们加了路径的重定向代码pathRewrite,上述代码以正则匹配规则将以"/api"开头的请求地址修改为"",也就是说,我们这样配置后,当我们请求"/api/videoRecommend"的时候,会被重写为请求"/videoRecommend",直接在请求地址中将"/api"变成了"",由此刚好去掉了请求地址中多余的"/api",由此,上述的404错误就得到了解决。
https://api.apiopen.top/videoRecommend?id=127398正常接口当我们把pathRewrite重写的时候会把‘/api'在请求时变为空
测试:
跨域:
proxyTable: { //设置地址代理,跨域请求外部链接
'/vue-demo': {
target: 'https://easy-mock.com/mock/5b6127a76551d73d713927c4/',
changeOrigin: true,
pathRewrite: {
'^/vue-demo': '/vue-demo'
}
}
}
调用:
getdata(){
this.axios.get('/vue-demo/api/getdata').then((response)=>{
console.log(response.data)
}).catch((response)=>{
console.log(response)
})
}