首页 > 解决方案 > 如何修复“由于访问控制检查,Fetch API 无法加载 http://localhost:3000/static/js/0.chunk.js”

问题描述

我正在使用 React 构建一个通用的天气网络应用程序。现在我只是想获取一个城市的天气数据(即尚未做任何动态的事情)并将其记录在控制台中。

我正在使用 OpenWeatherMap API。

但是,每当我调用 API 时,都会出现以下错误:

  1. 由于访问控制检查,Fetch API 无法加载http://localhost:3000/static/js/0.chunk.js 。
  2. 错误:您提供的错误不包含堆栈跟踪。
  3. 未处理的承诺拒绝:类型错误:取消我想了解可能导致这些错误的原因以及如何解决它们。

以前,我曾尝试使用 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>
    )
}

标签: javascriptreactjsfetchfetch-api

解决方案


您需要将 weatherData 绑定到父组件才能在子组件中执行。为此,只需将其绑定到第一个组件的构造函数:

this.weatherData = this.weatherData.bind(this)

作为:

constructor(props) {
  super(props)
  this.state = {
   //blabla
   },
  this.weatherData = this.weatherData.bind(this)
}

推荐阅读