将用户保存到mongoose时出现Bcrypt错误

问题描述 投票:1回答:2

目前我正在按照教程推动自己进入主题节点+反应。

回购的链接是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...

Usermodel看起来像这样:

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;

谢谢你的帮助!

javascript node.js mongoose bcrypt
2个回答
0
投票

你的newUser.password未定义。我担心我们可以像这样访问mongoose docs。在这种情况下的解决方案是在.hash()中使用req.body.password

供参考:如果要访问mongoose doc的键值,则必须将doc解析为JSON。


0
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.