我正在尝试将 fetch 函数的响应转换为 json 格式,但是当我这样做时出现错误试图调用接口方法'java .lang.string com.facebook.react.bridge.ReadableMap.getString(java.lang.String)'上的空对象引用。
这是我的具有提取功能的代码段:
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键=类型,状态,确定,statusText,标题,URL,_bodyInit,_bodyBlod,bodyUsed” 。
bodyUsed = false
状态= 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()
中控制台获取结果时,我得到具有 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/中运行它时,它可以工作。因此原因隐藏在智能手机的代码执行内部。
答案 0 :(得分:0)
您的问题必须有更多的背景信息;请参见下面的代码段。显然可以。
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => console.log(json));