目录
1.安装sequelize和mysql2
2.在dao文件下新建dbConnect.js,连接数据库
3.下载dotenv,统一配置环境变量,对第二步的升级补充
4.自定义错误方法,根目录下新建utils文件夹,文件夹下新建文件errors.js
5.根目录下创建model文件夹,model文件夹下创建adminModel.js文件
6.dao文件夹下创建db.js文件
7.下载md5,实现加密
1.安装sequelize和mysql2
npm install --save sequelize mysql2
官网:入门 | Sequelize中文文档 | Sequelize中文网
2.在dao文件下新建dbConnect.js,连接数据库
//dbConnect.js
//连接数据库
const { Sequelize } = require("sequelize")
//创建连接
const sequelize = new Sequelize('mysite', 'root', 'root', {
host: 'localhost',
dialect: 'mysql', /* one of 'mysql' | 'postgres' | 'sqlite' | 'mariadb' | 'mssql' | 'db2' | 'snowflake' | 'oracle' */
logging: false
});
(async function () {
try {
await sequelize.authenticate();
console.log('Connection has been established successfully.');
} catch (error) {
console.error('Unable to connect to the database:', error);
}
}())
//app.js
//引入数据库链接
require("./dao/dbConnect")
3.下载dotenv,统一配置环境变量,对第二步的升级补充
//下载dotenv
npm i dotenv
//app.js,注意放在引入数据库链接的前面
//默认读取项目根目录下.env环境变量
require("dotenv").config();
//.env,写自己的数据库名字,密码什么的
DB_NAME=mysite
DB_USER=root
DB_PASS=root
DB_HOST=localhost
//dbConnect.js
//连接数据库
const { Sequelize } = require("sequelize")
//创建连接
const sequelize = new Sequelize(process.env.DB_NAME, process.env.DB_USER, process.env.DB_PASS, {
host: process.env.DB_HOST,
dialect: 'mysql', /* one of 'mysql' | 'postgres' | 'sqlite' | 'mariadb' | 'mssql' | 'db2' | 'snowflake' | 'oracle' */
logging: false
});
(async function () {
try {
await sequelize.authenticate();
console.log('Connection has been established successfully.');
} catch (error) {
console.error('Unable to connect to the database:', error);
}
}())
4.自定义错误方法,根目录下新建utils文件夹,文件夹下新建文件errors.js
// 自定义错误
class ServiceError extends Error {
constructor(message, code) {
super(message);
this.code = code;
}
toResponseJSON() {
}
}
// throw new ServiceError('aaa', 123);
// 文件上传错误
export class UploadError extends ServiceError {
constructor(message) {
super(message, 413);
}
}
// 禁止访问错误
export class ForbiddenError extends ServiceError {
constructor(message) {
super(message, 401);
}
}
// 验证错误
export class ValidtionError extends ServiceError {
constructor(message) {
super(message, 406);
}
}
// 无资源错误
export class NotFoundError extends ServiceError {
constructor(message) {
super("not found", 404);
}
}
// 未知错误
export class UnKnownError extends ServiceError {
constructor(message) {
super("server internal error", 500);
}
}
module.exports.ServiceError = ServiceError
5.根目录下创建model文件夹,model文件夹下创建adminModel.js文件
const { DataTypes } = require("sequelize");
const sequelize = require("../dao/dbConnect");
// 定义数据模型
module.exports = sequelize.define("admin", {
loginId: {
type: DataTypes.STRING,
allowNull: false
},
name: {
type: DataTypes.STRING,
allowNull: false
},
loginPwd: {
type: DataTypes.STRING,
allowNull: false
},
}, {
freezeTableName: true,
createdAt: false,
updatedAt: false
})
6.dao文件夹下创建db.js文件
// 初始化数据库
const sequelize = require("./dbConnect");
const adminModel = require("../model/adminModel");
const md5 = require("md5");
(async function () {
//数据模型和表同步
await sequelize.sync({
alter: true,
})
//初始化数据
const adminCount = await adminModel.count();
if (!adminCount) {
await adminModel.create({
loginId: 'admin',
name: 'admin',
loginPwd: md5("123456")
})
console.log("初始化管理员数据完毕...")
}
console.log("数据库数据准备完毕...")
})()
7.下载md5,实现加密
npm i md5
//app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var adminRouter = require('./routes/admin');
var app = express();
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/api/admin', adminRouter);
//默认读取项目根目录下.env环境变量
require("dotenv").config();
//引入数据库链接
require("./dao/db")
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;