首页 > 解决方案 > 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));

标签: phpreact-native

解决方案


如您所见,您从 fetch() 获得的 Response 对象不仅仅包含正文。使用该json()函数读取正文并将其解析为 JSON。


推荐阅读