实际案例
db/index.js
const mysql = require('mysql')// 创建数据库的连接
const db = mysql.createPool({host: 'localhost',user: 'root',password: 'hxg20021126',database: 'management-pro'
})module.exports = db
LoginController.js
const db = require('../db/index')
const bcrypt = require("bcrypt");
const jwt = require('jsonwebtoken')
const jwtConfig = require('../config/JwtConfig')const register = (req, res) => {let {account, password} = req.body// 1. 非空和有效性校验if (!account || !password) {return res.send({code: 1,message: '账号或者密码为空'})}// 2. 账号是否已经存在// 参数: 执行语句 参数 回调函数处理结果db.query('select * from users where account = ?', account, (err, result) => {if (result.length > 0) {return res.send({code: 1,message: '账号已存在'});}// 3. 对注册的密码进行加密 参数: 值 加密后的长度password = bcrypt.hashSync(password, 10)// 4. 将账号和密码插入users表db.query('insert into users set ?', {account,password,identity: '用户',create_time: new Date(),status: 0}, (err, result) => {if (result.affectedRows !== 1) {//affectedRows 影响行数不唯一(没有影响到行数) 即插入失败return res.send({code: 1,message: '账号注册失败'})}res.send({code: 0,message: '账号注册成功'})})})}
const login = (req, res) => {const {account, password} = req.body// 查看数据库有无前端传过来的账号db.query('select * from users where account = ?', account, (err, result) => {// 一般会在数据库断开是执行失败if (err) return res.cc(err)if (result.length !== 1) return res.cc('未查询到数据,登录失败')// 对前端传过来的密码进行对比校验const compareResult = bcrypt.compareSync(password, result[0].password)if (!compareResult) {return res.cc('密码错误,登录失败')}// 对账号是否冻结做判定if (res[0].status === 1) {return res.cc('账号已被冻结')}// 返回token 给前端const user = {...result[0],password: '',imageUrl: '',create_time: '',update_time: ''}//生成token 设置有效时长为 6 个小时const tokenStr = jwt.sign(user, jwtConfig.jwtSecretKey, {expiresIn: '6h'})res.send({result: result[0],code: 0,message: '登录成功',token: 'Bearer ' + tokenStr})})
}
module.exports = {register,login
}
快速使用
var mysql = require('mysql');
var connection = mysql.createConnection({host : 'localhost',user : 'root',password : '123456',database : 'test'
});connection.connect();connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {if (error) throw error;console.log('The solution is: ', results[0].solution);
});