I have an issue with not getting just flash message on my page, but getting json with an error instead of it:
However, if I click "back" in browser, I see the page as expected, with flash message on it
My request code:
const handleLogin = async (req, res) => {
const { errors, isValid } = validateLoginInput(req.body);
if (!isValid) {
return res.status(422).json(errors);
}
const { email, password } = req.body;
const user = await User.findOne({email});
if (!user) {
errors.email = AUTH_ERROR;
req.flash('loginMessage', AUTH_ERROR);
return res.status(404).json(errors);
}
const isMatch = user.validatePassword(password, user.password);
const { id, role } = user;
if (isMatch) {
const payload = {id, email, role};
jwt.sign(
payload,
config.JWTAuthKey,
{expiresIn: 3600},
(err, token) => {
res.cookie(tokenCookieName, token, { maxAge: 60 * 60 * 24 * 7 , httpOnly: false });
res.redirect('/');
}
);
} else {
errors.password = AUTH_ERROR;
req.flash('loginMessage', AUTH_ERROR);
return res.status(403).json(errors);
}
};
In addition, my passport config (I use jwt strategy)
const config = (passport) => {
passport.use(
new Strategy(opts, (jwt_payload, done) => {
User.findById(jwt_payload.id)
.then((user) => {
if (user) {
return done(null, user);
}
return done(null, false);
})
/*eslint no-console: ["error", { allow: ["warn", "error"] }] */
.catch(err => console.error(err));
}),
);
};
Any ideas would be highly appreciated, thank you un advance.
It turned out to be pretty easy. No need to send back status, just
return res.redirect('/')
will do the trick. One can redirect wherever is needed.