node+express+jwt验证+加密

var express = require('express');
var router = express.Router();
const Users = require('../models/users.js')
const bcrypt = require("bcryptjs")
const jwt = require("jsonwebtoken")

process.env.SECRET_KEY = "secret"

/* GET users listing. */
router.get('/', (req, res, next) => {
  res.json({
    code: 1,
    data: "res",
    msg: "成功"
  })
});
// 注册 
router.post('/register', (req, res, next) => {
    // console.log(req.body)

    const now = new Date()
    const userData = {
      name: req.body.name,
      password: req.body.password,
      age: 18,
    }
    // cun 
    Users.findOne({
      where: {
        name: userData.name
      }
    }).then((user) => {
      console.log('传递的数据', userData)
      if (!user) {
        // 加密
        bcrypt.hash(req.body.password, 10, (err, hash) => {
          userData.password = hash
          Users.create(userData).then(user => {
            console.log('成功')
            res.json({
              status: user.name + "注册成功"
            })
          }).catch(err => {
            res.send("error" + err)
          })
        })

      } else {
        console.log(user + '已经注册')

        res.json({
          status: user.name + "已经注册了"
        })
      }
    })
    // console.log('ends')
  }),
  // 登录
  router.post("/login", (req, res) => {
    console.log(req.body)
    Users.findOne({where:{name:req.body.name}}).then(user=>{
      // 查找用户
      if(user){
        if(bcrypt.compareSync(req.body.password,user.password)){
          console.log("登录成功")
          let token = jwt.sign(user.toJSON(),process.env.SECRET_KEY,{
            expiresIn:1440
          })
          // res.send("登录成功")
          res.json({msg:"登录成功",token})
        }else{
          console.log("密码错误")
          res.send("密码不正确")
        }
      }else{
        console.log("未找到用户错误")
        res.status(400).json({error:"用户不存在"})
      }


    })
    .catch(err => res.send("error22" + err))

  })



// end
module.exports = router;
posted on 2021-12-10 10:21  哼着老调调  阅读(190)  评论(0编辑  收藏  举报

聊天   切换waifu!  换衣服!   拍照!   许愿吧cxy