'Promise { <pending> } React bcrypt hashing the Password [duplicate]
I am creating a Login/Registration Form Using Nodejs. I am hashing the password entered by the user using bcrypt.js but when I assign the password to a variable so that I push that to the database I get this error "Promise { pending }". I am learning nodejs and react so I do not know too much about this can someone help me. Thanks!
The Code That I am running is:
################################
const express = require('express');
const app = express();
const mysql = require('mysql2');
const bcrypt = require('bcryptjs');
const cors = require('cors');
// Need this to make api request from backend
app.use(cors());
/**using this express will format the data automatically in json format */
app.use(express.json()); /**Use This Otherwise you get the req.body undefined */
const port = 3001;
const securePassword = async (password) => {
const passwordHash = await bcrypt.hash(password, 4);
return passwordHash;
};
const db = mysql.createConnection({
user: 'root',
host: 'localhost',
password: 'newpassword',
database: 'INSTAGRAM',
});
// Getting Data From Signup Form of React
app.post('/signup', (req, res) => {
const emailaddress = req.body.emailaddress;
const fullname = req.body.fullname;
const username = req.body.username;
const password = req.body.password;
const hashPass = securePassword(password);
console.log(hashPass);
// Checking If Use Already Exist
db.query(
'SELECT * FROM USER WHERE username = ? OR email = ? ',
[username, emailaddress],
(err, result) => {
if (err) {
res.send({ err: err });
} else {
if (result.length > 0) {
res.send({ message: 'Username/Email Already Exist' });
} else {
db.query(
'INSERT INTO USER (username, fullname, email, password) VALUES (?, ?, ?, ?)',
[username, fullname, emailaddress, hashPass],
(err, result) => {
if (err) {
res.send(err);
} else {
res.send(result);
}
}
);
}
}
}
);
});
// Starting the server on port 3001
app.listen(port, () => {
console.log(`SERVER STARTED ${port}`);
});
Solution 1:[1]
First of all for better and more professional coding try to break your code into multiple functions in multiple .js files . then you should pass a function to validate the inputs otherwise any data can be passed to db without being validated . and then you can use this codes for user Registration :
app.js file :
const express = require('express');
const app = express();
const userRouter = require('./routes/user.routes');
app.use(express.json());
app.use('/user', userRouter);
user.routes file :
const express = require('express');
const userRouter = express.Router();
const {httpHandleSignUp} = require('../controllers/user/user.controller');
userRouter.post('/signup', httpHandleSignUp);
module.exports = userRouter
and then for handling Registration you can create a controller file and first of all check the inputs :
httpHandleSignUp controller code :
async function handleSignUp(req, res) {
const values = req.body
const errors = await validateInputs(values, res);
if(errors.length == 0) {
await addUserToDB(values, res);
} else {
res.json(errors)
}
}
you can use any validation you want like code below :
async function validateInputs(values, res) {
let errors = [];
if(!values.name || !values.email || !values.password) {
errors.push('missing required inputs');
}
if(!/\S+@\S+\.\S+/.test(values.email)) { // regex : [email protected]
errors.push('invalid email address ');
}
if(values.password.length < 8) {
errors.push('entered password is too short !');
}
if(await checkDbForEmail(values.email)) {
errors.push('a user with this email already registered !');
}
// TODO : add more validation
return errors;
}
and also you need to a function to check db for already registered users which used in above function :
async function checkDbForEmail(email) {
return await user.findOne({
email: email
});
}
now if there is NO errors the user will be added to DB by this function :
async function addUserToDB(values, res) {
bcrypt.hash(values.password, saltRounds)
.then(hashedPass => {
user.create({
name: values.name,
email: values.email,
password: hashedPass
}, (err, user) => {
res.json({
ok : 'user added to db successfully',
data: {
name: user.name,
email: user.email
}
});
});
})
.catch( (err) => console.log(err));
}
tip: this code works with mongo you may need to changes DB functions.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
