我正在开发一个反应-本土项目,以学习为目的。我使用的是RapidAPI (https://rapidapi.com/divad12/api/numbers-1/endpoints)。
当我点击API时,状态为200 in,但我无法从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();
}In console.log(响应);I get:

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

如何以JSON格式读取响应体?
发布于 2019-10-08 19:06:50
当前您正在打印response对象,该对象包含原始响应,包括标头等。您可以执行以下操作:
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();
}发布于 2019-10-08 20:25:41
我也有过同样的问题。当从RapidApi嵌入spoonacular时。然后我用了这个:
<?php
$headers = array('Accept' => 'application/json');
$response = Unirest\Request::get("https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/search?number=50&query='.$plus_separated.'",
array(
"X-RapidAPI-Key" => "bc038c4c88mshae2640d....e1acp1301aejsnd5703df78862"
)
);
$array_1 = $response->raw_body;
}
?>
<div id="result_body" class="container">
<P id="allert_msg" class="text-center">Results Not Found</P>
</div>
<script>
var array_2 = '<?php echo $array_1;?>';
var array_3 = JSON.parse(array_2);
var main_array = array_3.results;
var main_array_length = main_array.length;
var i=j=k=l=m=0;
for(i=0; i < main_array_length; i++){
var result_body= document.getElementById("result_body");
var body_link = document.createElement("a");
body_link.setAttribute("class", "single_link");
body_link.setAttribute("target", "_blank");
body_link.setAttribute("href", 'recipe_details.php?id='+main_array[i].id+'&submit_id=OK');
result_body.appendChild(body_link);
var p = document.createElement("div");
p.setAttribute("id", "single_item_"+j++);
p.setAttribute("class", "single_item");
body_link.appendChild(p);
</script>是为了食谱搜索的目的。代码自动创建div,a,p,.等HTML DOM元素,并将显示搜索结果。您应该以json格式将正确的值放到来自响应的正确位置。在上面,我将响应放在PHP中的"$array_1“中,然后放在Javascript中的"array_2”中。然后用Javascript继续下一个过程。如果您在我的代码中出现了一些错误,并且有了更好的想法,请让我了解一下。谢谢!
https://stackoverflow.com/questions/58282983
复制相似问题