首页 > 解决方案 > 使用 fetch 方法读取 RapidAPI JSON 响应

问题描述

我正在开发一个用于学习目的的 react-native 项目。我正在使用 RapidAPI ( https://rapidapi.com/divad12/api/numbers-1/endpoints ) 来做同样的事情。

当我点击 API 时,我的状态为 200OK,但我无法从 API 读取 JSON 格式的响应数据。

代码:

fetchCurrencyData = () => {
    fetch("https://numbersapi.p.rapidapi.com/7/21/date?fragment=true&json=true", {
        "method": "GET",
        "headers": {
            "x-rapidapi-host": "numbersapi.p.rapidapi.com",
            "x-rapidapi-key": "<Valid API Key, generated in code snippet>"
        }
    })
    .then(response => {         
        console.log(response);
    })
    .catch(err => {
        console.log(err);
    }); 
}

componentDidMount(){
    this.fetchCurrencyData();
}

在 console.log(response); 我得到:

在此处输入图像描述

我检查了 RapidAPI -> MyApps 部分中的响应:

在此处输入图像描述

如何读取 JSON 格式的响应正文?

标签: javascriptjsonapireact-nativefetch

解决方案


当前您正在打印响应对象,其中包含原始响应,包括标头等。您可以执行以下操作:

fetchCurrencyData = () => {
    fetch("https://numbersapi.p.rapidapi.com/7/21/date?fragment=true&json=true", {
        "method": "GET",
        "headers": {
            "x-rapidapi-host": "numbersapi.p.rapidapi.com",
            "x-rapidapi-key": "<Valid API Key, generated in code snippet>"
        }
    })
    .then(response => response.json()) // Getting the actual response data
    .then(data => {         
        console.log(data);
    })
    .catch(err => {
        console.log(err);
    }); 
}

componentDidMount(){
    this.fetchCurrencyData();
}

推荐阅读