框架怎么搭建,看下面即可:
vscode+nodejs+express 搭建一个简单网站
要在 Node.js + Express 中从数据库获取数据,需要借助数据库驱动(比如 mssql),下面是完整步骤:
一、准备工作
- 安装依赖:
npm install express mssql # mssql是SQL Server的Node.js驱动
二、完整代码示例(连接 SQL Server 并查询数据)
// 2. 定义接口:从数据库查询数据
app.get('/get-data-bjqinfo', async (req, res) => {
let pool;
try {
// 连接数据库(创建连接池)
pool = await sql.connect(dbConfig);
// 执行SQL查询(查询你截图里的表,假设表名是`你的表名`,请替换成实际表名)
const result = await pool.request().query('SELECT * FROM bjqinfo');
// 返回查询结果
res.json({
code: 0,
msg: '查询成功',
data: result.recordset // recordset是查询到的数据集
});
} catch (error) {
console.error('数据库操作失败:', error);
res.status(500).json({
code: -1,
msg: '服务器异常',
error: error.message
});
} finally {
// 关闭连接池(可选,连接池会自动管理,但手动关闭更安全)
if (pool) {
await pool.close();
}
}
});
运行一下看结果:

看,查到了数据库里面的数据。
533

被折叠的 条评论
为什么被折叠?



