[英]React.js Using axios to send integer data but get [object object] in Node.js
[英]Cannot get response from node.js to react.js using GET call
在使用Ajax调用时,我正在尝试从后端获取数据
componentDidMount: function () {
$.ajax({
url: 'http://127.0.0.1:3000/ap/test',
dataType: 'json',
success: function (data) {
this.setState(data);
}.bind(this), error: function (xhr, status, err) {
// console.error(this.props.url, status, err.toString());
console.error('failed to view user');
}.bind(this)
});
这是我在node.js中的Get呼叫
app.get('/test', function(req, res) { DBs.find({},function(err,data){
if(err){ throw err;}
else {
console.log('GET API CALLED, Data Sent!');
} sendingData = data;}); res.send(sendingData); });
1)调用了API,但未发送响应('获取API已调用,已发送数据!')
2)成功功能未在Ajax调用中运行,导致错误:“无法查看用户”
您的DBs.find()
调用将是asynchronous
,因此您需要从DBs.find
的回调函数发送数据
app.get('/test', function(req, res) {
DBs.find({}, function(err, data) {
if (err) {
throw err;
} else {
console.log('GET API CALLED, Data Sent!');
res.send(data);
}
});
});
@ShubhamKhatri说的对,对res.send
的调用应该在回调函数中,这样才能在知道数据库查找结果后运行。
但是还有另一个错误:您在发送结果之前忘记将结果转换为JSON字符串。 然后res.send
需要一个字符串(或者可能是一个缓冲区),所以我想它只是发送data.toString()
,它可能是[object Object]
或类似的东西。 由于您使用了dataType: 'json'
,因此jQuery尝试将其读取为JSON字符串。 但这不是有效的JSON,因此将调用error函数。
要解决此问题,只需调用JSON.stringify
:
app.get('/test', function(req, res) {
DBs.find({}, function(err, data) {
if (err) {
throw err;
// BTW you might want less drastic error handling in this case. I'd say just send an HTTP 500 response and log something.
} else {
console.log('GET API CALLED, Data Sent!');
res.send(JSON.stringify(data));
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.