zoukankan      html  css  js  c++  java
  • 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('秘密输入有误,请再输入一次');
    
      }),
    
    
    ]
    View Code

    bcrypt密码加密解密中间件

    body.password = await bcrypt.hash(body.password, 10) // 密码加密
    const match = await bcrypt.compare(value, currentUser.password); // 明文 ,加密密码
     
     
  • 相关阅读:
    spring 动态创建数据源
    现有‘abcdefghijkl’12个字符,将其所有的排列按字典序进行排序,给出任意一组排列,说出这租排列在所有排列中是第几小的
    javaweb项目运行时错误
    StringUtils.isEmpty和StringUtils.isBlank用法和区别
    启动项目时tomcat问题汇总
    hibernate 在web.xml中配置的作用
    Java几种常见的编码方式
    struts学习总结
    Javaweb开发中关于不同地方出现的绝对路径和相对路径
    解决中文乱码问题
  • 原文地址:https://www.cnblogs.com/xiaoliziaaa/p/13368761.html
Copyright © 2011-2022 走看看