Reputation: 2081
I'm new to javascript ecosystem and want to add jwt token to response out of this registration router:
router.post('/register', (req, res)=> {
User.findOne({email: req.body.email})
.then(user => {
if(user) {
return res.status(400).json({error: 'Email already exists'});
} else {
const newUser = new User({
username: req.body.username,
email: req.body.email,
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.status(200).json(user)) //<=Problem is here
.catch(err => console.log(err));
} )
})
}
})
});
The jwt snippet (which works fine on longin
router) is this:
const payload = {
username: user.username
}
//sign token
jwt.sign(
payload,
keys.secretOrKey,
{ expiresIn: 3600},
(err, token)=> {
res.json({
success: true,
token: 'Bearer '+ token,
username: username
});
});
The problem is that I don't know how can I add the snippet to the response header.
When I add it after .then(user =>
I get a SyntaxError: Unexpected token const
error.
How can I make it?
Upvotes: 0
Views: 146
Reputation: 1296
Sounds like you didn't wrap the jwt snippet within curly braces. Without them the arrow function where the problem appears only takes one expression. Paste the jwt snippet into the following snippet instead.
bcrypt.genSalt(10, (err, salt)=> {
bcrypt.hash(newUser.password, salt, (err, hash)=> {
if (err) throw err;
newUser.password = hash;
newUser.save()
.then(user => {
res.status(200).json(user);
<JWT_Snippet_here>
}
.catch(err => console.log(err));
})
})
Here you can see how the syntax of arrow functions is defined. The following quote shows the most important part.
(param1, param2, …, paramN) => { statements }
(param1, param2, …, paramN) => expression
Curly braces are needed in order to be able to use a list of statements. The error you experienced occurred because your JavaScript engine expected a single expression but instead found a list of statements.
Upvotes: 2