【问题标题】:Fetch res.json() Attempt to invoke intergace method 'java.lang.String...'Fetch res.json() 尝试调用接口方法'java.lang.String ...'
【发布时间】:2019-04-28 16:03:12
【问题描述】:

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

这是我的带有 fetch 功能的代码 sn-p:

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);
    })
}

UPDATE_2

我已经用另一个 url 运行了 fetch 函数,但问题仍然存在。似乎.json() 导致错误。当我试图在第一个 .then() 中控制 fetch 的结果时,我得到带有 type、status 等键的 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))
}

UPDATE_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/ 中运行它时,它可以工作。所以原因隐藏在智能手机上的代码执行中。

【问题讨论】:

  • 在第一个之后添加第二个then.then(res=>res.json()).then(res=>"now res is json");
  • 感谢您的评论,但没有帮助。请参阅“更新”部分。
  • 你的 react native 版本号是多少?
  • "react": "^16.8.3" and "react-native": "^0.59.4"

标签: javascript json reactjs react-native fetch


【解决方案1】:

你的问题必须有更多的背景;请参阅下面的 sn-p。这显然有效。

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

【讨论】:

  • 似乎是 .json() 函数导致了错误。我已经运行了你的 sn-p 但得到了同样的错误。
  • 也许您的浏览器没有实现fetch api? developer.mozilla.org/en-US/docs/Web/API/…
  • 我正在使用 React-Native 创建一个 Android 应用程序。对于测试,我使用物理智能手机。那里的 Chrome 版本是 73.0.3683.90
猜你喜欢
  • 1970-01-01
  • 2015-11-13
  • 2018-11-20
  • 2018-11-21
  • 1970-01-01
  • 1970-01-01
  • 2016-04-23
  • 2015-12-10
  • 2015-08-07
相关资源
最近更新 更多