【问题标题】:How to fix 'Fetch API cannot load http://localhost:3000/static/js/0.chunk.js due to access control checks'如何修复“由于访问控制检查,Fetch API 无法加载 http://localhost:3000/static/js/0.chunk.js”
【发布时间】:2019-11-11 02:26:16
【问题描述】:

我正在使用 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>
    )
}

【问题讨论】:

  • 问题中引用的Fetch API cannot load http://localhost:3000/static/js/0.chunk.js due to access control checks 错误消息与问题中显示的对https://api.openweathermap.org 的请求无关。相反,您的代码在其他地方向 http://localhost:3000/static/js/0.chunk.js 发出请求,问题是您的 http://localhost:3000 服务器显然没有启用 CORS。

标签: javascript reactjs fetch fetch-api


【解决方案1】:

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

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

作为:

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

【讨论】:

    【解决方案2】:

    您需要完全采用一种方法或使用另一种方法:

    基本 React.Component 类示例:

    constructor(props) {
      //...
      this.weatherData = this.weatherData.bind(this);
    }
    
    async weatherData() {/* your code */}
    

    或者,使用沉着的方法:

    weatherData = () => {/* ... */}
    

    您的镇静是分配一个function(),它重新绑定this 的上下文。您需要分配一个箭头函数() =&gt; {} 来保留this,以免发现自己迷路了this

    解决绑定问题的最佳方法是使用函数式方法:

    function WeatherThing() {
      const weatherData = async () => {
        const weatherInfo = await weatherDataFetch();
      }
    
      return (<div onClick={weatherData}>Do Weather stuff</div>);
    }
    

    我建议阅读 React Hooks 以使您的代码更具可读性。

    【讨论】:

      【解决方案3】:

      我更改了我的开发环境的主机名并遇到了同样的问题。

      如果您重新启动浏览器或机器,问题应该会消失。

      【讨论】:

        猜你喜欢
        • 2020-10-18
        • 2022-11-04
        • 2023-01-28
        • 2020-11-18
        • 2020-12-18
        • 1970-01-01
        • 1970-01-01
        • 2010-10-07
        • 1970-01-01
        相关资源
        最近更新 更多