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.

Vue2前端请求API数据跨域问题解决

问题解决:

最简单的方法是在前端配置跨域请求

1. 在Vue项目的vue.config.js文件添加内容如下:

module.exports={
    devServer:{
        proxy:{
        	//设置允许跨域的路径(以api为例)
            '/api':{
            //设置允许跨域请求的域名(以我请求的api域名为例)
                target: 'http://dzq.wenlvnews.com/index.php/yiqing/push.html',
             // secure: false,  // 如果是https接口,需要配置这个参数
                changeOrigin:true,
                pathRewrite: {
                    '^/api': ''
                }
            }
        }

    }
}

2. 获取api接口数据:

mounted(){ //页面渲染后再触发
		// api接口请求的数据
		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) {
		        // console.log(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中文文档

Logo

前往低代码交流专区

更多推荐