将用户保存为猫鼬时的Bcrypt错误

时间:2018-09-08 13:07:23

标签: javascript node.js mongoose bcrypt

此刻,我正在按照一个教程将自己推向主题节点+做出反应。

回购链接为https://bitbucket.org/grtn/cloudstruct/src/develop/

当我向/ api / users / register发出发布请求时,在控制台中出现以下错误,我不知道为什么。

/Users/****/Dev/cloudstruct/routes/api/users.js:38
                        if(err) throw err;
                                ^

Error: Illegal arguments: undefined, string
    at _async (/Users/****/Dev/cloudstruct/node_modules/bcryptjs/dist/bcrypt.js:214:46)
    at Object.bcrypt.hash (/Users/****/Dev/cloudstruct/node_modules/bcryptjs/dist/bcrypt.js:220:13)
    at bcrypt.genSalt (/Users/****/Dev/cloudstruct/routes/api/users.js:37:28)
    at Immediate.<anonymous> (/Users/****/Dev/cloudstruct/node_modules/bcryptjs/dist/bcrypt.js:153:21)
    at runCallback (timers.js:756:18)
    at tryOnImmediate (timers.js:717:5)
    at processImmediate [as _immediateCallback] (timers.js:697:5)
[nodemon] app crashed - waiting for file changes before starting...

用户模型如下:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// Create Schema
const UserSchema = new Schema({
    name:{
        type: String,
        required: true
    },
    email:{
        type: String,
        required: true
    },
    password:{
        type: String,
        required: true
    },
    avatar:{
        type: String
    },
    date:{
        type: Date,
        default: Date.now
    }
});

module.exports = User = mongoose.model('users', UserSchema);

我的路线:

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 post route
//@access   Public
router.get('/test', (req, res) => res.json({msg: '<h1>Hello World</h1>'}));

//@route    POST 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',
                    r: 'pg',
                    d: 'mm'
                });

                const newUser = new User({
                    name: req.body.name,
                    email: req.body.email,
                    avatar: 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));
                    })
                });
            }
        });
});

module.exports = router;

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

您的newUser.password未定义。恐怕我们可以像这样访问猫鼬文档。在这种情况下,解决方案是在.hash()

中使用req.body.password

供参考:如果要访问猫鼬文档的键值,则必须将文档解析为JSON。

答案 1 :(得分:0)

使用Mogoose哈希密码的正确方法是使用presave middleware。这样可以保证无论您要在何处创建用户记录,都将始终对用户密码进行哈希处理。而且,对于架构而言更好:散列将在数据层而不是路由中进行。

Here是一个很好的例子。中间件在步骤2中进行了描述。