【问题标题】:Not able to log a fetch's result无法记录提取结果
【发布时间】:2021-07-06 15:37:02
【问题描述】:

我目前正在使用 nodejs,我创建了一个服务器端函数,该函数从数据库返回并打印数据。

app.get('/renderMainDashboard', (req,res)=>{ //DASHBOARD DATA
    con.connect(err => {
        if (!err){
            con.query("SELECT * FROM owners", (err, data, fields) =>{
                console.log(data); //IT LOGS THE DATA INTO DE VS TERMINAL
                return data;
            })
        }
    });
});

我需要从客户端调用这个函数,所以有一个类可以在构造函数中进行获取:

export default class{
    constructor() {
        this.title = "Dashboard";
        
        fetch('http://localhost:5600/renderMainDashboard') //DEFAULT GET ()
        .then(response => response.json())    
        .then(finalResponse => {console.log('Datos recibidos desde el server', finalResponse);});
        //DOESN'T LOG 'Datos recibidos...' TO WEB CONSOLE
       //.then(console.log('Response from then statement'); //IT DOES THE LOG
    }
//----
}

该功能确实有效,当我尝试获取时它仍然有效,但我需要记录响应。如您所见,有一个带有 console.log('Datos recibidos...') 的 then 语句,但它不起作用。知道我可能做错了什么吗?

数据库的实际输出:

[
  TextRow {
    id: 1,
    firstName: 'Andres',
    lastName: 'Gonzalez',
    email: 'androsogt@gmail.com',
    personalKey: 'androso+1234-',
    phoneNumber: '35006115'
  },
  TextRow {
    id: 2,
    firstName: 'Pedro',
    lastName: 'Contreras',
    email: 'sirpedro@gmail.com',
    personalKey: 'holamundo',
    phoneNumber: '41508886'
  },
  TextRow {
    id: 3,
    firstName: 'Yuhana',
    lastName: 'Melgar',
    email: 'melgar.keyla@gmail.com',
    personalKey: 'COD2002',
    phoneNumber: '37578639'
  }
]

【问题讨论】:

  • .then(finalResponse => {console.log('Datos recibidos desde el server: ', finalResponse);});
  • 控制台有错误吗?可能是未处理的拒绝错误?
  • 不,控制台没有任何错误。我不明白为什么它在不声明 finalResponse 时打印它(只是做一个随机的 console.log('XD'))

标签: javascript node.js json database fetch


【解决方案1】:

您不会通过发送响应来结束您的请求。看这个例子:

app.get('/', function (req, res) {
  res.send('hello world')
})

您应该使用res.send() 方法来结束您的请求并发送回数据。

为什么不记录?因为 response.json() 由于没有响应(超时)而返回一个被拒绝的承诺,因此第二个 .then 不会被调用。

【讨论】:

    【解决方案2】:

    您的 express get /renderMainDashboard 处理程序没有向客户端发送任何内容。

    尝试替换:

    return data;
    

    与:

    res.status(200).json(data); // provided that data is a valid JSON object
    

    【讨论】:

      猜你喜欢
      • 2013-06-13
      • 2020-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-18
      • 1970-01-01
      • 2017-07-02
      相关资源
      最近更新 更多