Vue2前端请求API数据跨域问题解决方法
前端:Vue2
接口使用:API
问题报错提示:
Access to XMLHttpRequest at 'http://localhost:9090/echarts/members' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
问题解决:
最简单的方法是在前端配置跨域请求
1. 在Vue项目的vue.config.js文件添加内容如下:
module.exports={
devServer:{
proxy:{
'/api':{
target: 'http://dzq.wenlvnews.com/index.php/yiqing/push.html',
changeOrigin:true,
pathRewrite: {
'^/api': ''
}
}
}
}
}
2. 获取api接口数据:
mounted(){
var that = this;
this.axios({
methods: "**get**",
headers: {
ContentType: "application/json",
"Access-Control-Allow-Origin": "*",
},
dataType: "json",
ContentType: "application/json;charset-utf-8",
url: "**/api**",
data: {},
})
.then(function (response) {
that.dataapi = response.data;
})
.catch(function (error) {
console.log(error);
});
}
3. 渲染前端页面
<el-col :span="6">
<el-card style="color: #DD6161;">
<div>现有确诊</div>
<div style="padding: 10px 0; text-align: center; font-weight: bold;">
<div v-for="item in dataapi" :key="item.allData">{{ item.diagnosed }}</div>
</div>
</el-card>
</el-col>
4. 跨域问题完美解决
axios中文文档
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)