如何在Fetch()中处理JSON?API请求无响应问题排查
排查fetch请求无响应问题
核心问题及修复方案:
API密钥未替换
代码中{secret}是占位符,必须替换为你在OpenWeatherMap申请的真实API密钥,否则请求会被服务器拒绝(通常返回401状态码)。Promise链语法错误&逻辑缺失
原代码存在多处语法和逻辑问题:console.log(fetch(...))直接打印Promise对象,无法获取实际响应;- 第二个
then被注释,导致解析后的JSON数据无法被处理; - 箭头函数代码块未闭合,缺少
});结束回调; displayJson函数定义后未被调用。
本地文件运行的CORS限制
如果直接用file://协议打开HTML文件,浏览器会触发CORS限制,导致请求失败。建议用本地服务器(比如Node.js的http-server)运行项目,以http://协议访问。
修正后的JavaScript代码示例:
const getDataButton = document.getElementById("get-data-button"); getDataButton.addEventListener("click", () => { // 替换为你的真实OpenWeatherMap API密钥 const apiKey = "你的API密钥"; fetch(`https://api.openweathermap.org/data/2.5/weather?lat=47.6&lon=-122.3&appid=${apiKey}`) .then(response => { // 校验响应状态 if (!response.ok) { throw new Error(`请求失败,状态码:${response.status}`); } return response.json(); }) .then(data => { console.log(data); displayJson(data); }) .catch(error => { // 捕获所有请求相关错误 console.error("请求出错:", error); }); }); function displayJson(json) { console.log(json); }
额外排查步骤:
打开浏览器开发者工具,查看Network面板:
- 确认请求是否发送成功,查看状态码;
- 查看响应内容,服务器会返回具体错误信息(比如密钥无效、参数错误等)。
内容的提问来源于stack exchange,提问作者uncanny-vegan-taco
相关产品推荐
相关产品推荐

