I'm using node.js and bcryptjs to register a new user and save their name/email/password to mongoDB in mlab.
Here is my code
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 users route
// @access Public
router.get("/test", (req, res) => res.json({ msg: "Users Works" }));
// @route GET 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", // Size
r: "pg", // Rating
d: "mm" // Default
});
const newUser = new User({
name: req.body.name,
email: req.body.email,
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));
});
});
}
});
});
// @route GET api/users/login
// @desc Login User / Returning JWT Token
// @access Public
module.exports = router;
If I comment out line 37 "if(err) throw err;" I'm able to store the user credentials but the password will not store ( using postman )
The error I receive is ..
Error: Illegal arguments: undefined, string at _async (C:\Users\Cody\Desktop\DevSoc\node_modules\bcryptjs\dist\bcrypt.js:214:46) at Object.bcrypt.hash (C:\Users\Cody\Desktop\DevSoc\node_modules\bcryptjs\dist\bcrypt.js:220:13) at bcrypt.genSalt (C:\Users\Cody\Desktop\DevSoc\routes\api\users.js:36:16) at Immediate._onImmediate (C:\Users\Cody\Desktop\DevSoc\node_modules\bcryptjs\dist\bcrypt.js:153:21) at runCallback (timers.js:789:20) at tryOnImmediate (timers.js:751:5) at processImmediate [as _immediateCallback] (timers.js:722:5)
Where is this coming from? I can't see an error in my code.
Thanks
newUser.passwordcontain? Actually log it on a request and find out. The error would indicate this isundefined.req.body. Log it and then look back to the request being made if it's not even there. Check you have a body parser set up. If neither of those apply then it's more likely a problem with your model. Probably masking a field or similar.