vue中解决axios请求第三方接口跨域问题


一、问题描述

调用第三方,高德地图天气接口报错,如下

Access to XMLHttpRequest at 'https://restapi.amap.com/v3/weather/weatherInfo?key=f50e7061863b2673d26b0b657ad85809&city=310100&extensions=all' from origin 'http://localhost:8080' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

 

二、分析问题,发现是跨域问题

跨域指浏览器不允许当前页面的所在的源去请求另一个源的数据。源指协议,端口,域名。只要这个3个中有一个不同就是跨域。

 

三、解决方法

以高德地图   https://restapi.amap.com/v3/weather/weatherInfo?key=f50e7061863b2673d26b0b657ad85809&city=310100&extensions=all  为例 ,请求上海的天气;会报错的

axios.get("https://restapi.amap.com/v3/weather/weatherInfo?key=f50e7061863b2673d26b0b657ad85809&city=310100&extensions=all")
.then(res=>{
    console.log(res)
})
.catch(err=>{
    console.log(err)
})

 

1.前提这里是使用vue脚手架生成的标准项目为准。一般在项目config目录下面有个index文件

  dev: {
    autoOpenBrowser: true,
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      '/gdWeather': {
        target:'https://restapi.amap.com/v3', // 你请求的第三方接口
        changeOrigin:true, // 在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题
        pathRewrite:{  // 路径重写,
          '^/gdWeather': ''  // 替换target中的请求地址,也就是说以后你在请求http://api.douban.com/v2/XXXXX这个地址的时候直接写成/api即可。
        }
      }
    },
  }

注意:每个人的项目可能配置是不一样的,我的项目中就没有这个config目录,这个配置代理是放在vue.config.js文件中的

 

2.在main.js文件,配置一下axios.defaults.baseURL ='/gdWeather'

 

 

 

3.在组件中axios请求数据使用

    this.$axios({
      method: "get",
      url:
        "/weather/weatherInfo?key=f50e7061863b2673d26b0b657ad85809&city=310100&extensions=all",
    })
      .then((res) => {
        console.log(res);
      })
      .catch((err) => {
        console.log(err);
      });

 

 

 

 4、访问第三方接口成功

 

 

 

 

参考地址:https://blog.csdn.net/wh_xmy/article/details/87705840   https://www.jianshu.com/p/0eb0fd72cdbc

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM