首页 > 解决方案 > Fetch res.json() 尝试调用接口方法'java.lang.String ...'

问题描述

我正在尝试将fetch函数的响应转换为json格式,但是当我这样做时,我得到一个错误Attempt to invoke interface method 'java.lang.string com.facebook.react.bridge.ReadableMap.getString(java.lang. String)' 在空对象引用上

这是我的带有 fetch 功能的代码片段:

export const fetchAllUsers = () => {
fetch('http://192.168.1.103:3000/api/userData')
    .then(res => {
        res.json();
        //console.warn('res keys = ' + Object.keys(res))
    })
}

如果用console.warn评论该行,我会看到以下"res keys = type, status, ok, statusText, headers, url, _bodyInit, _bodyBlod, bodyUsed"

bodyUsed = 假

状态 = 200

类型 = 默认

为什么我不能将响应转换为json格式?还是有其他方法可以做到这一点?

更新

我已经添加了第二个then,但我仍然收到错误并且console.warn('res is json')没有运行:

export const fetchAllUsers = () => {
fetch('http://192.168.1.103:3000/api/userData')
    .then(res => {
        res.json();
        //console.warn('res keys = ' + Object.keys(res));
    })
    .then(res => {
        console.warn('res is json');
        console.warn(res);
    })
}

更新_2

我已经fetch用另一个 url 运行了函数,但仍然有问题。似乎.json()导致错误。当我试图在第一次控制 fetch 的结果时,我得到带有类型、状态等键的.then()json 对象。

export const fetchAllUsers = () => {
    fetch(`http://${localIP}:${port}/api/userData`)
        //.then(res => res.json())
        .then(json => console.warn('JSON: ' + json))
        .catch(e => console.warn('ERROR: ' + e))
}

更新_3

忘了提到我正在使用 React Native 创建一个 Android 应用程序。为了测试,我正在使用物理智能手机。Chrome 版本有 73.0.3683。

我已将fetch查询替换为以下内容:

fetch('https://jsonplaceholder.typicode.com/todos/1')
    .then(response => response.json())
    .then(json => console.log(json));

但仍然得到同样的错误。

当我在https://jsfiddle.net/中运行它时,它可以工作。所以原因隐藏在智能手机上的代码执行中。

标签: javascriptjsonreactjsreact-nativefetch

解决方案


你的问题必须有更多的背景;请参阅下面的代码段。这显然有效。

fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(json => console.log(json));


推荐阅读