问题描述
下面的代码总是返回下面的连线对象
The below code always return the below wired object
{_U":0,_V":0,_W":空,_X":空}
{"_U": 0, "_V": 0, "_W": null, "_X": null}
作为回应.
这是我的代码
getData = () => {
fetch('http://192.168.64.1:3000/getAll',{
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
}
})
.then((response) => {
console.log('Response:')
console.log(response.json())
console.info('=================================')
})
.catch(err => console.error(err));
}
componentDidMount(){
this.getData();
}
我使用 node、express、Mysql 作为后端和 react-native 前端
I am using node, express, Mysql as backend and react-native frontend
我的后端代码在这里
app.get('/getAll',(req,res) => {
console.log('getAll method Called');
con.query('select * from dummy',(err,results,fields) => {
if(err) throw err;
console.log('Response');
console.log(results);
res.send(results);
});
});
上面的代码在控制台中给出了正确的输出,但 fetch API 不是.
The above code gives correct output in console but fetch API is not.
我找不到我的问题的解决方案.提前致谢.
i cant find solution for the my problem. Thanks in advance.
推荐答案
这表明您在 promise 解决之前记录了它 - 当您执行以下操作时的结果:console.log(response.json())
That indicates that you are logging the promise before it resolves - the result of when you:
console.log(response.json())
如何访问 promise 回调值在函数之外?
正如@Evert 在评论中正确指出的那样,这是因为 response.json() 返回了一个 promise 对象.
As @Evert rightfully pointed out in comments, this is because response.json() returns a promise object.
因此,在您调用 response.json()
后,您需要链接一个额外的 .then()
,并在其中记录已解决的承诺.
So, you'll need to chain an additional .then()
after you call response.json()
where you log the resolved promise.
getData = () => {
fetch('http://192.168.64.1:3000/getAll',{
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(err => console.error(err));
}
这篇关于fetch API 总是返回 {“_U": 0, “_V": 0, “_W": null, “_X": null}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!