部署到Firebase后OpenWeatherMap API无法正常工作问题求助
问题根因
Firebase Hosting站点默认使用HTTPS协议,你代码中调用openweathermap接口、加载天气图标用的都是HTTP协议,浏览器的混合内容安全策略会直接拦截HTTPS站点发起的HTTP请求,因此线上部署后接口调用失败。本地localhost环境没有这类严格的跨协议拦截限制,所以本地运行完全正常。
修复方案
把代码中所有HTTP开头的openweathermap相关链接统一替换为HTTPS即可,具体修改两处:
- 接口请求地址:将
http://api.openweathermap.org改为https://api.openweathermap.org - 天气图标地址:将
http://openweathermap.org/img/wn/改为https://openweathermap.org/img/wn/
修改后的核心代码片段如下:
// 接口请求部分修改 axios.get(`https://api.openweathermap.org/data/2.5/weather?q=${place}&appid=${APIKey}`) .then(responce=>{ setDataIN(responce) console.log(responce) }) .catch(error=>{ console.log(error) setFetchError(true) }) // 图标加载部分修改 <img src={`https://openweathermap.org/img/wn/${dataIN.data.weather[0].icon}@2x.png`} alt="Icon"/>
修改完成后重新执行打包命令生成build文件夹,再部署到Firebase Hosting即可正常调用接口。
内容的提问来源于stack exchange,提问作者Sukarna Jana
相关产品推荐
相关产品推荐

