React调用OpenWeatherMap API遇跨域及请求取消错误排查与解决
问题分析与解决方法
首先咱们来拆解你遇到的两个错误,核心问题其实很明确:
1. TypeError: cancelled 错误的根源
这个是最关键的问题——表单提交的默认行为会触发页面刷新。当你点击提交按钮时,浏览器会立刻重新加载页面,直接中断了正在进行的fetch请求,导致Promise被强制取消,也就抛出了TypeError: cancelled。而你在componentDidMount里能正常请求,是因为那个时机没有页面刷新的干扰,请求能完整走完整个流程。
至于那个Fetch API cannot load http://localhost:3000/static/js/0.chunk.js...的错误,大概率是页面刷新时的连带误报,解决了表单刷新的问题后这个错误也会跟着消失。
2. 具体修复步骤
只需要在处理表单提交的函数里阻止浏览器的默认提交行为就行,修改起来非常简单:
修改主App里的weatherData函数
给函数添加event参数,然后调用event.preventDefault()来阻止页面刷新:
weatherData = async function(event) { // 先阻止表单默认的页面刷新行为 event.preventDefault(); try { const resp = await fetch('https://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=APP-ID'); const data = await resp.json(); console.log(data); } catch (err) { console.log(err) } }
额外优化:获取用户输入的城市和国家
现在你的代码里请求的是固定的伦敦,后续可以改成读取表单里用户输入的值,比如在weatherData里这样写:
weatherData = async function(event) { event.preventDefault(); // 从表单元素里获取用户输入的城市和国家 const city = event.target.city.value; const country = event.target.country.value; try { const resp = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city},${country}&appid=APP-ID`); const data = await resp.json(); console.log(data); } catch (err) { console.log(err) } }
为什么用AccuWeather也有同样问题?
本质原因完全一致——都是表单提交触发页面刷新,打断了API请求,和你使用哪个天气API没有关系。
内容的提问来源于stack exchange,提问作者Debabrata Mondal
相关产品推荐
相关产品推荐

