3
votes

I am trying to add a salt to my password but I have this error:

(node:12652) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'value' of undefined

(node:12652) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)

(node:12652) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

my auth/index.js

const bcrypt = require('bcrypt');
const saltRounds = 10;
const myPlaintextPassword = 's0/\/\P4$$w0rD';
const someOtherPlaintextPassword = 'not_bacon';

const salt = bcrypt.genSaltSync(saltRounds);

exports.modules = {
    salt
}

my controller:

const Users = require('../models/users');
const bcrypt = require('bcrypt');
const { salt } = require('../auth/index');

const getUsers = ((req,res) => 
    Users.findAll()
    .then((result) => { 
        res.json(result) 
    })
    .catch((error) => { res.json(error) })
    )

const addUsers = (async (req,res,next) => {
    const name = req.body.name;
    const email = req.body.email;
    let password = bcrypt.hashSync(req.body.password, salt.value);
    const data = {
        name,
        email,
        password
    }; 
    console.log(data);
    Users.create(data)
    .then((result) => { res.json(result) })
    .catch((error) => { res.json(error) });
});

module.exports = {
    getUsers,
    addUsers,
    Users
}
1
This error is likely happening when you try to call salt.value, so salt appears to be undefined. Are you sure you're importing what you think you are?Nick
@nick no u can help me with this? I followed bcrypt's walkthroughuser12356906

1 Answers

1
votes

You exported a salt function. You are trying to access it's object which is of course undefined because this object has no property name value. So, it gives you a UnhandledPromiseRejectionWarningerror. Salt function already return a value.

And one more thing, it should be module.exports in auth/index.js.

You should return a value from function. This is how you can rewrite the whole process.

index.js

const bcrypt = require('bcrypt');
const saltRounds = 10;
const myPlaintextPassword = 's0/\/\P4$$w0rD';
const someOtherPlaintextPassword = 'not_bacon';

module.exports.salt= function(){
return bcrypt.genSaltSync(saltRounds); }

You may await for the salt function in the controller level.

let password = await bcrypt.hashSync(req.body.password, salt());

That's it. Now, I think your code will work.