reactjs - 如何修复 react-native 中的 GET JSON 响应问题

标签 reactjs react-native

我正在使用来 self 的 React Native 应用程序的 API。但是请求响应总是返回一个字符串,即使我尝试解析我也看到错误。

我使用了 axios、superagent 和 fetch api。但我仍然面临一个错误,同样的错误。

fetch(`http://fonte83.com.br/wp-json/wp/v2/posts?page=1&_embed`, {
            method: "GET",
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/x-www-form-urlencoded',
            }
        }).then(result => result.json()).then(text => console.log(text))

此代码在导航器控制台或其他应用程序上运行良好,但在我的应用程序上却一团糟。 我尝试使用此代码在 axios 中转换另一个代码,但仍然遇到错误。

if (typeof data === 'string') {
             try {
                 if (!String.prototype.trim) {
                     String.prototype.trim = function () {
                         return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
                     };
                 }
                 data = JSON.parse(data.trim(''));
             } catch (e) {
                 throw {message: 'can not JSON.parse the response'}
             }
         }

我收到此错误: “位置 0 处的 JSON 中的意外标记”。

上面这两个代码来自不同的尝试

有什么奇怪的,因为代码在其他位置运行。 谁能帮帮我?

最佳答案

Fetch API 在 Promise result.json() 上返回一个 JSON 对象,因此您的代码应该是:

fetch(`http://fonte83.com.br/wp-json/wp/v2/posts?page=1&_embed`, {
        method: "GET",
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/x-www-form-urlencoded',
        }
    }).then(result => result.json())
      .then(obj => {
         console.log('Title of the first post: ' + obj[0].title.rendered);
         console.log('Content of the first post: ' + obj[0].content.rendered);
    });

您正在尝试解析一个已被 result.json() 解析的对象

关于reactjs - 如何修复 react-native 中的 GET JSON 响应问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55579245/

相关文章:

reactjs - 在休息编辑时访问管理员中的当前记录

javascript - 脚本 1002 : Syntax error in IE11 with React + Babel + Webpack

reactjs - React 测试库和 Jest 中的模拟路由器

android - 在不重新启动应用程序的情况下将 native 应用程序 LTR 更改为 RTL 更改

javascript - React Native 中的 `fetch` 未从 URL 返回预期数据

javascript - Fetch 请求出现 500 错误;请求的资源上不存在 'Access-Control-Allow-Origin' header

javascript - window.onscroll 箭头功能在 Safari 中不起作用

python - 有没有办法在 React Native 应用程序中使用我的 Python 代码?

macos - 如何使用 Rosetta 在 Mac 上解决 'react-native' 和 cocopods 的错误

react-native - 发现世博会未捕获错误 : The snack @snack/sdk. 32.0.0