I am getting the "Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client" error in my code.
router.get("/", verify, async (req, res) => {
const user = await pool.query("SELECT * FROM users WHERE id = $1", [req.user]);
if (user.rows.length) {
return res.status(200).json({ user: user.rows[0] });
} else {
return res.status(403).json({ msg: "Not Authorized" });
}
});
Below is the verify middleware,
try {
const { auth } = req.cookies;
if (!auth) {
return res.status(403).json({ msg: "Not Authorized" });
} else {
const data = jwt.verify(auth, process.env.JWT_SECRET);
req.user = data.id;
next();
}
} catch (error) {
return res.status(403).json({ msg: "Not Authorized" });
}
next();
I will be glad if someone helps.
CodePudding user response:
If the else
branch of the verify
middleware is taken, next()
is executed twice. This leads to two executions of the other middleware and hence to two responses, which causes the observed error.