React调用OpenWeatherMap API出现JSON解析Unexpected token <报错
React调用OpenWeatherMap API触发JSON解析报错的排查与解决
报错信息:App.js:31 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
这个报错的核心原因是:req.json()在解析响应内容时,收到的不是预期的JSON格式数据,而是以<开头的HTML内容(一般是HTML文档的起始<html>标签),因此解析直接失败。
你的原始代码
class App extends React.Component { constructor() { super(); this.state = { data: [], }; this.getWeather(); } getWeather = async () => { const url = 'api.openweathermap.org/data/2.5/weather?q=toronto&appid=' + apiKey; let req = await fetch(url); let res = await req.json(); } }
逐点排查修复
- 1. 接口URL缺失协议前缀
你拼接的地址api.openweathermap.org/...没有加https://协议头,浏览器会把这串字符判定为相对路径,自动拼接成当前React开发服务的本地地址(比如http://localhost:3000/api.openweathermap.org/...),这个地址返回的是React开发服务的默认HTML首页,内容以<开头,必然触发JSON解析报错。
修复方式:补全URL的协议头,写法为:const url = 'https://api.openweathermap.org/data/2.5/weather?q=toronto&appid=' + apiKey; - 2. 未做响应状态校验,异常场景下直接执行JSON解析
即便补全URL,如果接口返回非200状态(比如apiKey无效、参数错误、新申请的key未生效)、或被网络规则拦截,都可能返回HTML格式的错误内容。需要在解析JSON前先校验响应状态,补充异常捕获,避免出现未处理的Promise抛出:getWeather = async () => { const url = 'https://api.openweathermap.org/data/2.5/weather?q=toronto&appid=' + apiKey; try { const req = await fetch(url); if (!req.ok) { // 异常场景下先读取响应文本,抛出可读错误,避免直接解析JSON触发无意义报错 const errContent = await req.text(); throw new Error(`请求失败,状态码${req.status},响应内容:${errContent}`); } const res = await req.json(); // 拿到正常数据后同步更新组件状态 this.setState({ data: res }); } catch (error) { console.error('获取天气数据失败:', error); } } - 3. 开发环境跨域拦截
若补全URL、加完异常捕获后,发现请求仍被重定向到本地地址,属于跨域限制导致的请求被拦截:- 确认注册的OpenWeatherMap apiKey已完成激活,新申请的key通常需要5-10分钟的生效等待期
- 如果是用Create React App初始化的项目,可在根目录
package.json中添加代理配置"proxy": "https://api.openweathermap.org",之后请求时可直接写相对路径/data/2.5/weather?q=toronto&appid=xxx,绕开开发环境的跨域限制。
内容的提问来源于stack exchange,提问作者Milan Patel
相关产品推荐
相关产品推荐

