TypeError:“尝试获取资源时出现NetworkError。”提取后

时间:2020-04-14 12:02:06

标签: fetch

我正在使用OpenWeatherAPI,这是我第二次使用获取时出现此错误:TypeError:“尝试获取资源时出现NetworkError。”。我之前已经使用过该API,并且可以正常工作,所以我很困惑这次触发该错误的原因。也许我使用的是相同的API密钥?我看到这个原因与CORS或网络安全有关,并且要解决此错误,我需要降低安全性或使用其他网络浏览器(我使用的是Firefox)。有没有更简单的解决方案,可以像以前一样正常获取代码?

import React from "react";

class OpenWeather extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            city: "",
        }
        this.handleInputChange = this.handleInputChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }
    handleInputChange(e) {
        this.setState({city: e.target.value})
    }
    async handleSubmit(e) {
        const cityName = this.state.city;
        const apiKey = "95f164c76ff59c438ecaa15889931a52";
        const url = `api.openweathermap.org/data/2.5/weather?q=${cityName}&appid=${apiKey}`;
        await fetch(url)
    .then(response => {
        return response.json();
    })
    .then(data => {
        console.log(data);
    })
    .catch(err => {
        console.log(err);
    });
    }
    render() {
        return (
            <div>
                <form onSubmit={this.handleSubmit}>
                <input id="city" type="text" name="name" placeholder="Enter city:" value={this.state.city} onChange={this.handleInputChange} />
                <button type="submit" value="Submit">Enter</button>
                </form>
            </div>
        )
    }
}
export default OpenWeather;

0 个答案:

没有答案