node中间件
npm i body-parser
post 请求主题中间件
const bodyParser = require(\'body-parser\')
const bodyParser = require(\'body-parser\') // 创建 application/json 解析 const jsonParser = bodyParser.json() app.use(jsonParser)
express-validator 表单校验中间件
const { body } = require(\'express-validator\');
const UserModel = require(\'../model/User\')
const bcrypt = require(\'bcrypt\')
/**
* 用户注册数据校验
*
*/
exports.addUserValidate = [
// name 不为空 string
body(\'name\').notEmpty().isString().withMessage(\'name字段不能为空且必须是string类型\'), //withMessage配置可有可无
// password 不为空 string
body(\'password\').notEmpty().isString().withMessage(\'password字段不能为空格且必须是string类型\'),
// 年龄数字 不为空 0<=age<=100
body(\'age\').notEmpty().isInt(), //isInt number类型验证失效
// userId字段数据数据库唯一 不为空 且为string
body(\'userId\').notEmpty().isString().custom(value => {
return UserModel.findOne({ userId: value }).then(user => {
if (user) {
return Promise.reject(\'userId 已存在\');
}
});
})
]
/**
* 用户登录数据校验
*
*/
let currentUser = null //用于保存当前
exports.userLoginValidate = [
body(\'userId\').notEmpty().isString().custom(value => {
return UserModel.findOne({ userId: value }).select(\'+password\').then(user => {
// 判断用户是否存在
if (!user) {
return Promise.reject(\'该用户id尚未注册\');
}
currentUser = user
});
}),
body(\'password\').notEmpty().isString().custom(async value => {
const match = await bcrypt.compare(value, currentUser.password); // 明文 ,加密密码
if (!match) return Promise.reject(\'秘密输入有误,请再输入一次\');
}),
]
bcrypt密码加密解密中间件
body.password = await bcrypt.hash(body.password, 10) // 密码加密
const match = await bcrypt.compare(value, currentUser.password); // 明文 ,加密密码