使用API Key请求OpenWeatherMap接口报404资源加载失败如何解决?
404错误产生原因
- 基础URL缺少协议前缀:你定义的
baseURL没有加https://前缀,浏览器会将其识别为当前站点的相对路径,自动拼接http://localhost:3000/前缀,导致请求地址完全错误,这是触发404的核心原因。 - 请求参数结构错误:OpenWeatherMap的邮编查询参数为
zip而非你写的id,且你在baseURL里提前预留了appid的拼接位,后续直接拼接邮编值会导致参数顺序混乱,服务端无法识别请求路径。 - 邮编值获取时机错误:
newZip是页面初始化时就获取的输入框值,此时用户尚未输入内容,拿到的是空值,进一步导致请求参数缺失。 - 错误捕获逻辑不完整:
fetch请求没有包裹在try代码块内,请求失败时会直接抛出未捕获异常,无法被后续的catch逻辑捕获处理。
对应解决方法
- 修正基础URL格式,补充
https://前缀,同时调整参数占位符为正确格式:// 可按需添加&units=metric参数,直接返回摄氏度单位的温度 let baseURL = 'https://api.openweathermap.org/data/2.5/weather?zip='; let apiKey = '23012caa6cd9437d2588b8f412b67f5f'; - 调整邮编值的获取时机,移到点击触发的函数内部,确保拿到用户最新输入的内容:
function performAction(){ // 点击时再获取用户输入的邮编和心情内容 let newZip = document.getElementById('zip').value; let feelingContent = document.getElementById('feelingLabel').value; getWeather(baseURL, newZip, apiKey, feelingContent); } - 修正请求拼接逻辑和数据读取逻辑,OpenWeatherMap返回的是对象格式,不是数组,需通过属性名读取对应值:
async function getWeather (baseURL, newZip, apikey, feelingContent){ try { // 按规范拼接完整请求地址 const res = await fetch(`${baseURL}${newZip}&appid=${apikey}&units=metric`) const projectData = await res.json(); // 直接通过属性名取对应值,时间戳可自行转换为可读日期格式 const date = new Date(projectData.dt * 1000).toLocaleDateString(); const temp = projectData.main.temp; // 渲染内容 const dateEl = document.createElement('div'); const tempEl = document.createElement('div'); const contentEl = document.createElement('div'); const feelingEl = document.createElement('div'); dateEl.innerHTML = `日期:${date}`; tempEl.innerHTML = `温度:${temp}℃`; contentEl.innerHTML = `天气:${projectData.weather[0].description}`; feelingEl.innerHTML = `心情:${feelingContent}`; document.getElementById("container").append(dateEl, tempEl, contentEl, feelingEl); return projectData; } catch(error) { console.log("请求异常:", error); } }
内容的提问来源于stack exchange,提问作者Mohamed Hamissa
相关产品推荐
相关产品推荐

