一、問題描述
調用第三方,高德地圖天氣接口報錯,如下
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