router.post("/login", async (req, res) => {
try {
const user = await User.findOne({ username: req.body.username });
!user && res.status(401).json("Invalid credentials!");
const hashedPassword = CryptoJS.AES.decrypt(
user.password,
process.env.PASS_SEC
);
const originalPassword = hashedPassword.toString(CryptoJS.enc.Utf8);
originalPassword !== req.body.password &&
res.status(401).json("Invalid credentials!");
const { password, ...others } = user._doc;
res.status(200).json(others);
} catch (error) {
res.status(500).json(error.message);
}
});
When I post an incorrect username or an incorrect password I do get the correct HTTP Response Invalid Credentials!
However I receive an unhandled promise rejection error in my console log.
(node:12080) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at ServerResponse.setHeader (_http_outgoing.js:561:11) at ServerResponse.header (C:\Users\dinin\Projects\testexpress2\node_modules\express\lib\response.js:771:10) at ServerResponse.send (C:\Users\dinin\Projects\testexpress2\node_modules\express\lib\response.js:170:12) at ServerResponse.json (C:\Users\dinin\Projects\testexpress2\node_modules\express\lib\response.js:267:15) at C:\Users\dinin\Projects\testexpress2\routes\auth.js:24:21 at processTicksAndRejections (internal/process/task_queues.js:95:5) (node:12080) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag
--unhandled-rejections=strict(see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 4)
It's obviously in a try catch block. How can I "handle" this promise properly?