无法从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需要明确响应类型以避免编译错误,你可以:
- 定义响应接口(推荐)
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); // 可正常编译和访问 }) }
- 临时使用
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
相关产品推荐
相关产品推荐

