javascript - 使用 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 格式的响应正文?
解决方案
当前您正在打印响应对象,其中包含原始响应,包括标头等。您可以执行以下操作:
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();
}
推荐阅读
- typescript - 打字稿:如何从可能是也可能不是数组元素的泛型中推断类型
- r - 如何有选择地从数据框中的元素中删除字符?
- volttron - 如何在 Volttron-GS 中设置 ILC 代理?
- file - Applescript 选择文件夹中的最后一个文件(按名称升序列出)
- c# - 如何在 confuserex 中使用密码混淆符号名称?
- powershell - 管道中的具体类型输出变量无效的 JObject
- css - 如何使每个徽标在视觉上都具有相同的大小?
- javascript - 模拟路由器模块笑话
- python - 如果需要进行矩阵乘法,如何避免循环?
- python - 模块语法高亮