javascript - 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/中运行它时,它可以工作。所以原因隐藏在智能手机上的代码执行中。
解决方案
你的问题必须有更多的背景;请参阅下面的代码段。这显然有效。
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => console.log(json));
推荐阅读
- lisp - 使用循环使 UCI lisp 函数适应常见的 lisp
- c# - 使用数组显示文本文件中的字符串
- python-3.x - 在 odoov10 的 sale.order.line 中添加保留地段名称
- c# - 如何将接收到的数据从字符串复制到一维字符数组c#表单中
- javascript - React 中的平滑滚动
- angular - Mat Dialog在打开后改变它的背景
- dialog - 是否可以使用 InnoSetup 禁用成功卸载对话框
- python - 图像处理错误,“没有足够的值来解压”
- python - crfsuite中文本特征的数值转换
- matplotlib - 如何为圆圈设置动画以水平移动?