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

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中文文档

Vue 2 中,可以通过配置代理服务器或者使用 JSONP 来解决前端跨域问题。 1. 配置代理服务器:可以在 Vue 的配置文件 `vue.config.js` 中配置代理服务器,将前端请求转发给后端服务器。首先,创建一个 `vue.config.js` 文件,并添加以下内容: ```javascript module.exports = { devServer: { proxy: { '/api': { target: 'http://example.com', // 后端接口的域名 changeOrigin: true, pathRewrite: { '^/api': '' // 如果后端接口没有/api前缀,可以将其去除 } } } } }; ``` 上述配置将发往 `/api` 路径的请求转发给了 `http://example.com`,你可以根据实际情况修改这些配置。 2. 使用 JSONP:如果后端支持 JSONP,可以通过 JSONP 跨域来获取数据。在 Vue 中,可以使用第三方库 `vue-jsonp` 来方便地发送 JSONP 请求。首先,安装 `vue-jsonp`: ``` npm install vue-jsonp --save ``` 然后,在需要跨域请求的组件中,引入并使用 `vue-jsonp`: ```javascript import Vue from 'vue'; import VueJsonp from 'vue-jsonp'; Vue.use(VueJsonp); export default { methods: { fetchData() { this.$jsonp('http://example.com/api', { params: { // 请求参数 } }).then(response => { // 处理接口返回的数据 }).catch(error => { console.log('Error:', error); }); } } }; ``` 上述代码中,我们使用 `$jsonp` 方法发送跨域请求,并在 `then` 方法中处理接口返回的数据。 无论你选择使用代理服务器还是 JSONP,都可以解决 Vue 2 前端跨域问题。根据具体的需求和后端的支持情况,选择合适的方法来处理跨域
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值