php - fetch() 没有返回正确的 JSON
问题描述
我正在尝试使用 React Native 创建提要。我用 Ajax 得到了正确的数据,但是在 React Native 中,我得到了完全不同的东西。
这是您在浏览器中访问 URL 时返回的内容
PHP 脚本header('Content-Type: application/json');
位于顶部。
这是我获取 JSON 的函数。
getPostData()
{
fetch('https://url.com/api/globalfeed.php?skip=0' + '&key=' + this.state.user,
{
headers:
{
Accept: 'application/json',
'Content-Type': 'application/json',
},
})
.then((response) =>
{
console.log(response)
});
}
这是我的PHP
header('Content-Type: application/json');
// Compile all the data for the post to return it.
array_push($toReturn, [
'PostID' => $feedPost['PostID'],
'PostAuthor' => $feedPost['PostAuthor'],
'PostAuthorName' => $poster->data['FirstName'] . ' ' . $poster->data['LastName'],
'PostProfilePic' => $poster->data['ProfilePicture'],
'PostText' => embedEmojis($feedPost['PostText']),
'PostIsImage' => $feedPost['PostIsImage'],
'PostImageURL' => $feedPost['PostImageURL'],
'PostTime' => $feedPost['PostTime'],
'PostTimeFormatted' => timeElapsed('@'.$feedPost['PostTime']),
'PostLiked' => $liked,
'PostLikes' => $feedPost['PostLikes'],
'PostComments' => $cAr,
'Verified' => $poster->data['Verified'],
'Owned' => $owned
]);
die(json_encode($toReturn));
解决方案
如您所见,您从 fetch() 获得的 Response 对象不仅仅包含正文。使用该json()
函数读取正文并将其解析为 JSON。
推荐阅读
- python - 无法修复变量python
- podman - 使用 Podman 为容器分配特定的 IP 地址
- bash - ROS 启动文件仅在与启动文件位于同一文件夹时识别
- javascript - 在 Json 中搜索过滤器
- python - Selenium 请求在 Chrome 79 中运行缓慢
- formula - 使用自定义公式函数/自动化脚本的 Maximo 公式?
- php - 在 Web 根目录外的 Apache 2.4.29 上安装 SimpleSamlPHP 1.18.3
- node.js - 为什么我需要刷新页面才能在 react Express 中获得新状态
- xslt-1.0 - 基于节点元素递归拆分Xml
- laravel - 我们应该将 APNs p8 密钥存储在 Web 服务器的什么位置?