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

使用Node.js Express+MySQL实现MVC架构CRUD时数据库无返回数据问题求助

问题1:Model层回调函数参数顺序错误

你在Model中定义AirMonitoring.getAllData的回调逻辑时,成功响应的参数顺序传反了:

// 你的错误写法
result(res, null);

Node.js 回调约定是第一个参数为错误对象,第二个参数为返回结果,查询成功时应该改为:

result(null, res);

当前写法会把查询结果赋值给Controller里的err变量,真正接收数据的airMonitoring变量拿到的是null,自然返回空内容。


问题2:Controller层逻辑缺省花括号导致重复发送响应

你写的Controller判断错误的逻辑没有加花括号,触发if(err)条件时,只会执行res.send(err),后续的res.send(airMonitoring)还会执行,导致重复发送响应,触发控制台的Cannot set headers after they are sent to the client报错:

// 你的错误写法
if(err)
res.send(err);
console.log('data', airMonitoring);
res.send(airMonitoring)

正确写法需要加花括号,错误场景直接return终止执行:

exports.getAllData = (req, res)=> {
    AirModel.getAllData((err, airMonitoring) =>{
        if(err) {
            return res.send(err);
        }
        console.log('data', airMonitoring);
        res.send(airMonitoring)
    })
}

验证

修改上述两个问题后重启服务,再用Postman请求即可正常拿到数据库返回的记录,若还是无数据可先确认MySQL的AirMonitoring表中是否实际存储了有效记录。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 06:06:04