axios解决跨域
1、在config中的index.js文件中
将proxyTable后的内容修改为:
proxyTable: {
'/local_api':{
target: 'http://localhost:3000',
pathRewrite: {
'^/local_api': '/',
},
changeOrigin: true
},
},
其中'/local_api' 可以自己定义'/任意'
2、网络请求的地址就变成
http://localhost:3000/news -> /local_api/news
3、重启项目
代码示例:
index.js
proxyTable: {
'/local_api':{
target: 'http://localhost:3000',
pathRewrite: {
'^/local_api': '/',
},
changeOrigin: true
},
},
组件中的网络请求:
<template>
<div>
</div>
</template>
<script>
import qs from 'qs'
export default{
name:'d',
data()
{
return{
}
},
mounted()
{
this.$axios.get("/local_api/news")
.then(res=>{
console.log(res.data);
})
.catch(err=>{
console.log(err)
})
//这里未用qs处理post的参数,是因为在main.js中拦截器里处理了
this.$axios.post('/local_api/movie',{id:2}).then(res=>console.log(res.data)).catch(err=>console.log(err))
}
}
</script>
<style lang="css">
</style>