使用lat和long参数时按下openweathermap api后未接收任何数据

问题描述 投票:0回答:1

我想尝试OpenWeatherMap API。因此,我创建了一个React应用,在其中尝试了以下URL以获取天气数据

api.openweathermap.org/data/2.5/forecast?APPID={APPID}&id=524901&q=Mumbai

并且它没有任何问题,但是当我使用经度和纬度参数对其进行尝试时,它不起作用。此外,它不会引发任何错误。以下网址用于lat和long []

api.openweathermap.org/data/2.5/forecast?APPID={APPID}&lat=19.19&lon=72.95

我在浏览器和邮递员中尝试了上述URL,两次都收到了适当的数据。

这是我的代码,写在componentDidMount()中:

import './css/main.css';

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            lat: 19.196735,
            long: 72.95785599999999
        }
    }
    componentDidMount() {
        this.setCityName();
        let url = 'api.openweathermap.org/data/2.5/forecast?lat=' + this.state.lat + '&lon=' + this.state.long + '&appid={APPID}';

        console.log(url)

        fetch(url)
            .then(res => res.json())
            .then(
                (result) => {
                    console.log(result)
                    this.setState({
                        isLoaded: true,
                        list: result.list[0],
                        city: result.city.name,
                        country: result.city.country
                    });
                },
                (error) => {
                    this.setState({
                        isLoaded: false,
                        error: error
                    });
                }
            )
    }

    setCityName() {
        let success = (position) => {
            let lat = position.coords.latitude;
            let long = position.coords.longitude;
            this.setState({
                lat,
                long
            })
        }

        let error = () => {
            console.log('Can not find your location. Setting default location to Mumbai!');
        }

        if (!navigator.geolocation) {
            console.log('Geolocation is not supported in your browser. Setting default location to Mumbai!');
        }
        else {
            navigator.geolocation.getCurrentPosition(success, error);
        }
    }

    render() {
        console.log(this.state.list)
        return (
            <div className="app-container">
                <span className="location"><i className="fa fa-map-marker-alt"></i>{this.state.city}, {this.state.country}</span>
                {/* <div>{this.state.list}</div>ire */}
            </div>
        )
    }
}

export default App;

我想尝试OpenWeatherMap API。因此,我创建了一个React应用,其中我尝试使用以下URL来获取天气数据api.openweathermap.org/data/2.5/forecast?APPID={APPID}&id=524901&...

javascript reactjs openweathermap
1个回答
0
投票

我犯了一个愚蠢的错误。提取URL时未使用“ https://”。现在工作正常。

© www.soinside.com 2019 - 2024. All rights reserved.