unfortunately I can't seem to apply m understanding of promises to sequelize: On my login/authenticate route I'm trying to store my token linked to my user in my database but i'm getting the unhandled promise reection error : My method goes like this :
exports.authenticate = (req, res) => {
const credentials = req.body;
User.findOne({
where : {
email : req.body.login
}
})
.then((user) => {
if (!user) {
console.log('notfound!')
res.status(404).send("user not found");
} else {
if (bcrypt.compareSync(req.body.password, user.password)){
const token = jwt.sign({username : user.username}, secret.secret, {expiresIn : "2 days"});
Token.create({
code : token,
expired_at : sequelize.fn("DATEADD", sequelize.literal("day"), 2, sequelize.col(sequelize.fn('NOW')))
}).then((tkn) => {
console.log(tkn);
res.status(200).json(tkn.toJSON());
}).catch((e) => {
res.status(500).json({"message": "Server Error"});
});
res.status(200).json({message : "ok", token : token});
}else{
res.status(403).send('wrong password')
}
}
}).catch((e) => {
console.log(e);
res.status(500).send('unhandled Server error');
});
}
The Error message :
(node:15798) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client.
I tried creating my Token outside the find block but I'm getting my token variable is undefined. how can i go about storing my token after having created it .
I understood hat was going on, i had my outer promise going about it's thing and sending me the response
res.status(200).json({message : "ok", token : token});
while the promise of Toen.create was stuck on the way i chose to add two days to the current date with sequelize.
After commenting the response I got to handle the error in the Token.create block
I don't think this is the best way to do it so feel free to throw your two cents.
That's because code is sending response two times. first time it send response
res.status(200).json(tkn.toJSON());
and after it code become stuck whenever it get another response.
res.status(200).json({message : "ok", token : token});