javascript - 如何修复“由于访问控制检查,Fetch API 无法加载 http://localhost:3000/static/js/0.chunk.js”
问题描述
我正在使用 React 构建一个通用的天气网络应用程序。现在我只是想获取一个城市的天气数据(即尚未做任何动态的事情)并将其记录在控制台中。
我正在使用 OpenWeatherMap API。
但是,每当我调用 API 时,都会出现以下错误:
- 由于访问控制检查,Fetch API 无法加载http://localhost:3000/static/js/0.chunk.js 。
- 错误:您提供的错误不包含堆栈跟踪。
- 未处理的承诺拒绝:类型错误:取消我想了解可能导致这些错误的原因以及如何解决它们。
以前,我曾尝试使用 AccuWeather API,但它给出了相同的错误。
但是,如果我在 React 的 componentDidMount() 函数中调用 API,它会很好地获取数据。当我尝试在提交表单时获取天气数据时,问题就出现了。
这是我的主要应用程序代码:
weatherData = async function() {
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)
}
}
render() {
return (
<div>
<Title />
<Form loadWeather={this.weatherData} />
</div>
)
}
}
这是 React 组件:
import React from 'react';
import './Form.css';
const Form = (props) => {
return (
<form onSubmit = {props.loadWeather}>
<input className='input' type='text' name='city' placeholder='Enter City'></input>
<input className='input' type='text' name='country' placeholder='Enter Country'></input>
<button className='button'>Get Weather!</button>
</form>
)
}
解决方案
您需要将 weatherData 绑定到父组件才能在子组件中执行。为此,只需将其绑定到第一个组件的构造函数:
this.weatherData = this.weatherData.bind(this)
作为:
constructor(props) {
super(props)
this.state = {
//blabla
},
this.weatherData = this.weatherData.bind(this)
}
推荐阅读
- ruby-on-rails - Capybara:在 form.submit() 上添加 setTimeout 时会话丢失
- android - 如何在另一个活动中显示基本活动的视图
- c# - 方程的迭代展开
- javascript - 将 JSON 查询条件转换为 MongoDB/Mongoose 操作
- javascript - 如何通过单击 Gatsby.js 中的按钮打开第三方小部件?
- javascript - 加快 node/express 应用程序中需要模块的速度
- java - 如何检测签名后 PDF 是否失效
- opencv - 如何检测空间图案的边缘?
- javascript - 在网格内查找随机放置的元素 (x,y)
- json - 尽管已在其他地方和 UTF-8 中进行了验证,但已验证的 JSON 在 Firebase 中产生了无效的 JSON 错误