个人博客(vue3 + nodejs + mysql + 腾讯云[99元/年 便宜货]服务器 + 宝塔可视化面板 纯手戳产物)http://124.223.41.220/
一、工具类代码如下:
/*
* @Description: ------ node连接并操作mysql封装 ------
* @Creater: snows_l snows_l@163.com
* @Date: 2023-04-12 15:38:57
* @LastEditors: snows_l snows_l@163.com
* @LastEditTime: 2024-04-09 16:16:04
* @FilePath: /Website/Server/utils/connDB.js
*/
class DBPool {
constructor() {
this.mysql = require('mysql');
this.config = require('../db.config.json');
//1.创建mysql连接对象
this.pool = this.mysql.createPool(this.config);
}
query(sql, params, callBack) {
//2.打开
this.pool.getConnection((err, connection) => {
if (err) {
// console.log('数据库连接失败', err);
throw err;
}
// console.log('数据库连接成功');
// 3.执行sql查询
connection.query(sql, params, (err, results, fields) => {
// 4.释放连接
connection.release();
// 5.销毁连接: 当连接不需要使用且需要从连接池中移除的时候,我们可以使用destory方法,该方法使用如下所示:
connection.destroy();
if (err) {
// console.log('数据库操作失败');
throw err;
}
// console.log('数据库操作成功');
callBack && callBack({ results, fields });
});
});
}
queryAsync(sql, params) {
const self = this;
return new Promise((resolve, reject) => {
//2.获取连接
this.pool.getConnection((err, connection) => {
if (err) {
console.log('数据库连接失败', err);
reject(err);
return;
}
// console.log('数据库连接成功');
//3.执行sql查询
console.log('-------- sql --------',{ spl, params });
connection.query(sql, params, (err, results, fields) => {
connection.release(); //释放链接
connection.destroy(); //销毁链接
if (err) {
console.log('数据库操作失败');
reject(err);
return;
}
// console.log('数据库操作成功');
resolve({
results,
fields
});
});
});
});
}
}
module.exports = new DBPool();
mySql连接配置:
../db.config.json
{
"host": "124.223.41.220",
"port": 3306,
"user": "snows_l",
"password": "********",
"database": "websitdb"
}
二、使用如下:
/*
* @Description: ------------ fileDescription -----------
* @Author: snows_l snows_l@163.com
* @Date: 2024-04-15 14:29:31
* @LastEditors: snows_l snows_l@163.com
* @LastEditTime: 2024-04-17 16:02:27
* @FilePath: /Website/Server/src/router/user.js
*/
const express = require('express');
/*
* 引入工具类
*/
const db = require('../../utils/connDB');
const { name } = require('body-parser');
const { generateToken, verifyToken } = require('../../utils/handleToken');
// 解密前端的加密密码
const { decryptPwd } = require('../../utils/node-rsa');
const router = express.Router();
// 获取user列表
router.get('/user/list', (req, res) => {
const { page = 1, size = 10, role, name } = req.query;
let offset = (page - 1) * size;
let sql = `SELECT * FROM sys_user`;
let lensql = `SELECT count('user_id') FROM sys_user`;
if (name) {
sql += ` WHERE user_name LIKE '%${name}%'`;
lensql += ` WHERE user_name LIKE '%${name}%'`;
}
if (role) {
sql += ` ${name ? 'AND' : 'WHERE'} role = ${role}`;
lensql += ` ${name ? 'AND' : 'WHERE'} role = ${role}`;
}
selectSql = `${sql} ORDER BY user_id ASC LIMIT ${size} OFFSET ${offset};`;
// 参数的使用 数组的形式
// selectSql = `${sql} ORDER BY user_id ASC LIMIT ? OFFSET ?;`;
// const params = [size, offset];
/*
* 使用工具类的queryAsync异步方法操作sql数据库
*/
db.queryAsync(lensql).then(count => {
// 带参数
// db.queryAsync(selectSql, params).then(result => {
db.queryAsync(selectSql).then(result => {
res.send({
code: 200,
data: result.results,
msg: 'success',
total: count.results[0]["count('user_id')"]
});
});
});
});
在index中引入user.js接口文件即可
/*
* @Description: ------ 文件描述 ------
* @Creater: snows_l snows_l@163.com
* @Date: 2023-04-15 19:00:39
* @LastEditors: snows_l snows_l@163.com
* @LastEditTime: 2024-04-18 15:11:06
* @FilePath: /Website/Server/src/index.js
*/
const path = require('path');
const express = require('express');
// 对post请求的请求体进行解析
const bodyParser = require('body-parser');
// 主要用来解决客户端请求与服务端的跨域问题
const cors = require('cors');
// 引入路由
const sysRouter = require('./router/sys');
const favorsRouter = require('./router/favors');
const dictRouter = require('./router/dict');
const userRouter = require('./router/user');
const roleRouter = require('./router/role');
// 获取.env中的环境变量
const dotenv = require('dotenv').config({ path: './.env' });
// console.log('-------- dotenv --------', dotenv);
const jwtKey = process.env.APP_JWTKEY;
// console.log('-------- jwtKey --------', jwtKey);
const app = express();
app.use(bodyParser.json());
app.use(cors());
// 访问服务的接口
app.get('/', (req, res) => {
res.send('hello node server');
});
// 路由. (为了前端部署的时候nginx好做代理, 所以我同意了一个前缀)
app.use('/sys', sysRouter);
app.use('/sys', dictRouter);
app.use('/sys', favorsRouter);
app.use('/sys', userRouter);
app.use('/sys', roleRouter);
//设置静态资源访问路径 这样就可以直接通过 http://localhost:3333/filename 访问public目录下的静态资源文件
app.use(express.static(path.join(__dirname, '../public')));
// 服务启动在3333端口
app.listen(3333, () => {
console.log('-------- 服务启动了,运行在http://localhost:3333 --------');
});
如果有需要完整的项目吱一声。