node.js 连接sqlServer并创建接口
·
1.整体代码
const http = require('http');
const url = require('url'); // 用于解析 URL
const sql = require('mssql');
const sqlConfig = {
server: '192.168.x.x', // 数据库连接实例
database: 'xxx',
user: 'xxx',
password: 'xxx',
port: 1433,
options: {
encrypt: false,
trustServerCertificate: true // 对于本地开发环境,可以设置为true
},
pool: {
max: 10,
min: 0,
idleTimeoutMillis: 30000,
},
};
// 连接数据库
sql.connect(sqlConfig).then(() => {
console.log('数据库连接成功');
// 创建 HTTP 服务器
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true); // 解析 URL
const path = parsedUrl.pathname; // 获取路径
const method = req.method; // 获取 HTTP 方法
// 设置默认响应头(支持 JSON 和跨域)
res.setHeader('Content-Type', 'application/json');
res.setHeader('Access-Control-Allow-Origin', '*');
// 定义路由逻辑
if (path === '/api/user' && method === 'GET') {
// 处理 GET 请求 /api/user
res.writeHead(200);
res.end(JSON.stringify({ name: "John", age: 30 }));
} else if (path === '/api/data' && method === 'POST') {
// 处理 POST 请求 /api/data
let body = '';
req.on('data', chunk => {
body += chunk.toString(); // 接收请求数据
});
req.on('end', () => {
const data = JSON.parse(body);
res.writeHead(201);
res.end(JSON.stringify({ message: "Data received", input: data }));
});
}
if (path.startsWith('/api/getData') && method === 'GET') {
// 处理 GET 请求 /api/data/:id
// const id = path.split('/').pop();
const sqlScript = `
SELECT FORMAT(approveTime, 'yyyy-MM') AS 年月,
SUM(totalAmount) / 10000 AS 销售金额万元
FROM S_ContractItem
WHERE approveTime >= '2024-01-01'
AND status <> 'Cancel'
GROUP BY FORMAT(approveTime, 'yyyy-MM');
`;
// 执行SQL查询
new sql.Request()
// .input('id', sql.Int, id) // 接收API参数,传递给sqlScript参数@id
.query(sqlScript)
.then(result => {
console.log('SQL查询结果:', result);
// 将查询结果返回给API
res.writeHead(200);
res.end(JSON.stringify(result.recordset));
})
.catch(err => {
// 错误处理
console.error('SQL查询错误:', err);
res.writeHead(500);
res.end(JSON.stringify({ message: '服务器错误' }));
});
}
// {
// // 其他路径返回 404
// res.writeHead(404);
// res.end(JSON.stringify({ error: "Not Found" }));
// }
});
// 监听端口
const port = 3000;
server.listen(port, () => {
console.log(`服务器运行在 http://localhost:${port}`);
});
}).catch(err => {
console.error('数据库连接失败:', err);
});
2.按照依赖
用于连接sqlServer数据库
npm install mssql
3.访问
http://localhost:3000/api/getData
更多推荐
所有评论(0)