Javascript 无法使用get调用从node.js获取对react.js的响应

Javascript 无法使用get调用从node.js获取对react.js的响应,javascript,jquery,node.js,ajax,reactjs,Javascript,Jquery,Node.js,Ajax,Reactjs,在使用Ajax调用时,我试图从后端获取数据 componentDidMount: function () { $.ajax({ url: 'http://127.0.0.1:3000/ap/test', dataType: 'json', success: function (data) { this.setState(data); }.bind(this), error: funct

在使用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,但未发送响应。(“调用了GET API,发送了数据!”)

2) 成功函数未在Ajax调用中运行,导致错误:“未能查看用户”

您的
DBs.find()
调用将是
异步的,因此您需要从
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
的调用应该在回调函数内部,以便在已知数据库查找结果后运行

但还有另一个bug:在发送结果之前忘记将其转换为JSON字符串。然后,
res.send
需要一个字符串(或者可能是一个缓冲区),所以我想它只是发送
data.toString()
,这可能是
[object object]
或者类似的东西。由于您使用了
数据类型:“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));
        }
    });
});

仍然没有得到回应。使用
res.send(数据)就像你说的那样,在DB的回调中可以控制台.log(数据),是不是JSONONONONE?你可以在ajax成功调用中控制台.log(err)并与我共享输出吗?它运行,但它输出的是nothingTry logging xhr,看看你是否从中得到了什么。如果使用curl,你会从节点端点得到响应吗?