You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法从MySQL数据库向前端返回数据,请求排查问题

问题分析与解决:Node.js接口返回数据为空,前端无法获取数据库查询结果

问题现象

后端Node.js接口查询MySQL数据库后,控制台能正常打印出查询结果,但返回给前端时result字段为空;前端通过Angular的http.post请求接口,仅能收到message内容,尝试打印response.result时代码无法编译。

核心原因

Node.js中database.query是异步操作,你的代码在发起查询后立刻执行了res.status(200).json(...),此时数据库查询还未完成,result变量仍为初始的undefined,所以返回给前端的result是空的。

后端代码修正方案

把响应逻辑放到查询的回调函数内部,确保只有在数据库查询完成后才返回结果:

app.post('/api/user/database_test', (req, res, next) => {
  database.query('SELECT * FROM test', function (error, response, fields) {
    if (error) {
      // 错误处理,避免直接throw导致服务崩溃
      return res.status(500).json({ message: '数据库查询失败', error: error.message });
    }
    console.log('response:', response);
    // 查询完成后再返回数据
    res.status(200).json({
      message: 'Data from Database :',
      result: response
    })
  })
});

也可以用async/await语法让代码更直观(需使用支持Promise的MySQL库如mysql2/promise):

// 假设使用mysql2/promise的连接池
app.post('/api/user/database_test', async (req, res, next) => {
  try {
    const [response] = await database.query('SELECT * FROM test');
    res.status(200).json({
      message: 'Data from Database :',
      result: response
    });
  } catch (error) {
    res.status(500).json({ message: '数据库查询失败', error: error.message });
  }
});

前端代码修正方案

TypeScript需要明确响应类型以避免编译错误,你可以:

  1. 定义响应接口(推荐)
interface DbResponse {
  message: string;
  result: Array<{
    userid: string;
    username: string;
    firstname: string;
    lasname: string;
    email: string;
  }>;
}

async getFromDB() {
  const obj = 'test';
  this.http.post<DbResponse>('http://localhost:3000/api/user/database_test', obj)
    .subscribe((response) => {
      console.log('response: ', response);
      console.log('result: ', response.result); // 可正常编译和访问
    })
}
  1. 临时使用any类型(不推荐,失去TypeScript类型校验优势)
async getFromDB() {
  const obj = 'test';
  this.http.post<any>('http://localhost:3000/api/user/database_test', obj)
    .subscribe((response) => {
      console.log('response: ', response);
      console.log('result: ', response.result);
    })
}

内容的提问来源于stack exchange,提问作者helloworld

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 02:50:16