非法参数:未定义,字符串

时间:2018-10-25 06:39:16

标签: javascript node.js

注册用户时出现此错误:

  

(节点:13225)UnhandledPromiseRejection警告:错误:非法   参数:未定义,字符串       在Object.bcrypt.hashSync(/home/admin/Desktop/project/node_modules/bcryptjs/dist/bcrypt.js:189:19)       在module.exports.register(/home/admin/Desktop/project/controllers/auth.js:26:30)(节点:13225)   UnhandledPromiseRejectionWarning:未处理的承诺拒绝。这个   由抛出异步函数引起的错误   没有障碍,或者拒绝了没有处理的承诺   使用.catch()。(拒绝ID:1)

控制器:

const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const db = require('../config/db.config.js')
const User = db.user
const errorHandler = require('../utils/errorHandler')

module.exports.register = async function(req, res) {
    const candidate = await User.findOne({
        where: {
            username: req.body.username
        }
    })

    if (candidate) {
        res.status(409).json({
            message: 'This login is already taken. Try another.'
        })
    } else {
        const salt = bcrypt.genSaltSync(10)
        const password = req.body.password
        const user = new User({
            name: req.body.name,
            username: req.body.username,
            roles: req.body.roles,
            photoSrc: req.file ? req.file.path: '',
            password: bcrypt.hashSync(password, salt)
        })
        try {
            await user.save()
            res.status(201).json(user)
        } catch(e) {
            errorHandler(res, e)
        }
    }
}

型号:

module.exports = (sequelize, Sequelize) => {
    const User = sequelize.define('users', {
        name: {
            type: Sequelize.STRING(100),
            required: true
        },
        username: {
            type: Sequelize.STRING(40),
            required: true,
            unique: true
        },
        roles: {
            type: Sequelize.STRING(100),
            required: true
        },
        password: {
            type: Sequelize.STRING,
            required: true
        },
        photoSrc: {
            type: Sequelize.STRING(200),
            default: ''
        }
    });

    return User;
}

5 个答案:

答案 0 :(得分:1)

对于每个异步操作,我们都必须等待

const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(req.body.password, salt);

答案 1 :(得分:0)

您还需要将await应用于您的saltpassword分配。

喜欢这个

const salt = await bcrypt.genSaltSync(10);
const password = await req.body.password;

希望这会有所帮助!。

答案 2 :(得分:0)

以这种方式为我工作,而不是cb,您可以使用async-await

SFSafariApplication.getActiveWindow(completionHandler: { 
    $0?.openTab(with: url, makeActiveIfPossible: true) 
})

谢谢!

答案 3 :(得分:0)

我使用lambda函数遇到了相同的错误,但是我的问题是解析请求正文,所以我不得不

const body = JSON.parse(event.body) // in case of lambda function

希望这对某人有帮助。

答案 4 :(得分:0)

这是我在核对注册表时发现的,我正在寻找修复程序,但没有找到适当的解决方案。

我如何修复 后来我意识到,在发送发布请求之前,我没有传递必填字段。Before Sending Post request through Postman make sure You have passed key and value in postman

点击上方链接以查看示例。