node.js+express去连接sql server数据库,并创建连接池;使用axios实现前后端数据通信并实现对数据库的增删改查
时间: 2024-06-12 09:04:34 浏览: 285
首先,安装必要的npm包:
```
npm install express mssql axios body-parser --save
```
接下来,创建一个app.js文件:
```javascript
const express = require('express');
const bodyParser = require('body-parser');
const mssql = require('mssql');
const axios = require('axios');
const app = express();
// 配置body-parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// 配置mssql连接池
const pool = new mssql.ConnectionPool({
user: 'username',
password: 'password',
server: 'localhost',
database: 'database',
pool: {
max: 10,
min: 0,
idleTimeoutMillis: 30000
}
});
// 测试连接池是否正常工作
pool.connect().then(() => {
console.log('Connected to MSSQL');
}).catch(err => {
console.log(err);
});
// 实现路由
app.get('/users', (req, res) => {
pool.request()
.query('SELECT * FROM users')
.then(result => {
res.json(result.recordset);
})
.catch(err => {
console.log(err);
res.status(500).send('Server Error');
});
});
app.post('/users', (req, res) => {
const { name, age, email } = req.body;
pool.request()
.input('name', name)
.input('age', age)
.input('email', email)
.query('INSERT INTO users (name, age, email) VALUES (@name, @age, @email)')
.then(() => {
res.send('User added');
})
.catch(err => {
console.log(err);
res.status(500).send('Server Error');
});
});
app.put('/users/:id', (req, res) => {
const { name, age, email } = req.body;
const { id } = req.params;
pool.request()
.input('id', id)
.input('name', name)
.input('age', age)
.input('email', email)
.query('UPDATE users SET name = @name, age = @age, email = @email WHERE id = @id')
.then(() => {
res.send('User updated');
})
.catch(err => {
console.log(err);
res.status(500).send('Server Error');
});
});
app.delete('/users/:id', (req, res) => {
const { id } = req.params;
pool.request()
.input('id', id)
.query('DELETE FROM users WHERE id = @id')
.then(() => {
res.send('User deleted');
})
.catch(err => {
console.log(err);
res.status(500).send('Server Error');
});
});
// 启动服务器
app.listen(3000, () => {
console.log('Server started on port 3000');
});
// 测试axios前后端数据通信
axios.get('http://localhost:3000/users')
.then(res => console.log(res.data))
.catch(err => console.log(err));
axios.post('http://localhost:3000/users', { name: 'John', age: 30, email: 'john@example.com' })
.then(res => console.log(res.data))
.catch(err => console.log(err));
axios.put('http://localhost:3000/users/1', { name: 'John Doe', age: 32, email: 'johndoe@example.com' })
.then(res => console.log(res.data))
.catch(err => console.log(err));
axios.delete('http://localhost:3000/users/1')
.then(res => console.log(res.data))
.catch(err => console.log(err));
```
注意:在使用mssql连接池之前,需要先安装mssql的驱动程序:
```
npm install mssql --save
```
运行node app.js,即可启动服务器。使用axios发送请求,即可对数据库进行增删改查操作。
阅读全文