简体   繁体   中英

Unable to hash passwords with “bcryptjs” -> Console “Error: Illegal arguments: number, string”

I´m having an issue while hashing users passwords in the backend using bcryptjs in a Node/Express Server. When I try to use it following the official documentation I receive the above error. I've tried different ways without any solution. Please could you give me some ideas?

This is the hashing code

        const Usuario = require('../models/Usuario');
        const bcryptjs = require('bcryptjs');

        usuario = new Usuario(req.body);

        //Hashear Password
        const salt = await bcryptjs.genSalt(10);
        usuario.password = await bcryptjs.hash(password, salt);

        //Guardar Usuario
        await usuario.save();
        //Mensaje Confirmacion
        res.json({ msg: 'El usuario fue creado correctamente' });

And this is the users model

const mongoose = require('mongoose');

const UsuariosSchema = mongoose.Schema({
    nombre: {
        type: String,
        required: true,
        trim: true
    },
    email: {
        type: String,
        required: true,
        trim: true,
        unique: true
    },
    password: {
        type: String,
        required: true,
        trim: true
    },
    registro: {
        type: Date,
        default: Date.now()
    }
});

module.exports = mongoose.model('Usuario', UsuariosSchema);

Thanks in advance!!

the variable password passed to bcryptjs.hash must be string type as per their docs.

As in your above given snipped, couldn't identity where and when password is declare and its type.

i tried the below code and got error "illegal Argument: number, string"

var password = 1234;
const salt = await bcryptjs.genSalt(10);
var pass= await bcryptjs.hash(password, salt);

wherein the below code worked

var password = "1234";
const salt = await bcryptjs.genSalt(10);
var pass= await bcryptjs.hash(password, salt);
console.log(pass);

Output: 在此处输入图像描述

Can you check on the type value passed to the hash function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM