使用bcryptjs

时间:2018-04-24 22:40:35

标签: node.js mongodb bcrypt

我正在使用node.js和bcryptjs注册一个新用户并将他们的名字/电子邮件/密码保存到mlab中的mongoDB。

这是我的代码

const express = require("express");
const router = express.Router();
const gravatar = require("gravatar");
const bcrypt = require("bcryptjs");

// Load User model
const User = require("../../models/User");

// @route   GET api/users/test
// @desc    Tests users route
// @access  Public
router.get("/test", (req, res) => res.json({ msg: "Users Works" }));

// @route   GET api/users/register
// @desc    Register user
// @access  Public
router.post("/register", (req, res) => {
  User.findOne({ email: req.body.email }).then(user => {
    if (user) {
      return res.status(400).json({ email: "Email already exists" });
    } else {
      const avatar = gravatar.url(req.body.email, {
        s: "200", // Size
        r: "pg", // Rating
        d: "mm" // Default
      });

      const newUser = new User({
        name: req.body.name,
        email: req.body.email,
        avatar,
        password: req.body.password
      });

      bcrypt.genSalt(10, (err, salt) => {
        bcrypt.hash(newUser.password, salt, (err, hash) => {
          if (err) throw err;
          newUser.password = hash;
          newUser
            .save()
            .then(user => res.json(user))
            .catch(err => console.log(err));
        });
      });
    }
  });
});

// @route   GET api/users/login
// @desc    Login User / Returning JWT Token
// @access  Public

module.exports = router;

如果我在第37行注释“if(err)throw err;”我可以存储用户凭据,但密码不会存储(使用邮递员)

我收到的错误是..

错误:非法参数:undefined,string     在_async(C:\ Users \ Cody \ Desktop \ DevSoc \ node_modules \ bcryptjs \ dist \ bcrypt.js:214:46)     在Object.bcrypt.hash(C:\ Users \ Cody \ Desktop \ DevSoc \ node_modules \ bcryptjs \ dist \ bcrypt.js:220:13)     在bcrypt.genSalt(C:\ Users \ Cody \ Desktop \ DevSoc \ routes \ api \ users.js:36:16)     在Immediate._onImmediate(C:\ Users \ Cody \ Desktop \ DevSoc \ node_modules \ bcryptjs \ dist \ bcrypt.js:153:21)     在runCallback(timers.js:789:20)     在tryOnImmediate(timers.js:751:5)     at processImmediate [as _immediateCallback](timers.js:722:5)

这是从哪里来的?我在代码中看不到错误。

由于

1 个答案:

答案 0 :(得分:1)

您似乎正在将undefined密码传递给bcrypt.hash

要确保它没有到达那一点,请添加早期验证,可能是在POST路线的第一行:

router.post("/register", (req, res) => {
  const {email, password} = req.body
  if (!email || !password) {
    return res.send('Must include email and password')
  }
  ...
})