首页 > 解决方案 > 相同的 API 请求,一个得到响应并存储它,另一个没有

问题描述

所以我有两个来自不同 API 的获取请求。我不明白为什么这个:

let [responseObj, setResponseObj] = useState({});
fetch(`https://community-open-weather-map.p.rapidapi.com/weather?units=${unit}&q=${uriEncodedCity}`, {
            "method": "GET",
            "headers": {
                "x-rapidapi-host": "community-open-weather-map.p.rapidapi.com",
                "x-rapidapi-key": process.env.REACT_APP_API_KEY
            }
        })
            .then(response => response.json())
            .then(response => {
                if (response.cod !== 200) {
                    throw new Error()
                }

                setResponseObj(response);
                setLoading(false);
            })
            .catch(err => {
                setError(true);
                setLoading(false);
                console.log(err.message);
            });

获取并存储响应,但这个没有:

let [geoObj, setGeoObj] = useState({});
    
fetch(`http://api.openweathermap.org/geo/1.0/direct?q=${uriEncodedCity}&limit=1&appid=${Key}`, {
            "method": "GET"
        })
            .then(response => response.json())
            .then(response => {
                if (response.cod !== 200) {
                    throw new Error()
                }
                setGeoObj(response);
                console.log(response);
            })
            .catch(err => {
                setError(true);
                setLoading(false);
                console.log(err.message);
            });

在第二个请求中,api 密钥有效,在网络选项卡中,我从 API 获取 json,但是当我尝试将其存储在响应中并将其记录到控制台时,它显示为空白,而在第一个请求中,我得到了 json 响应.

标签: javascriptreactjsrest

解决方案


我认为这是因为其中一个是一个数组,而您正试图将它存储在一个对象中——看看useState({}).

我在codeandbox中尝试了这段代码,它工作正常。


推荐阅读