const router = require("express").Router();
const user = require("../models/user");
const cryptoJs = require("crypto-js");
const dotenv = require("dotenv").config();
router.post("/register", async (req, res) => {
const newUser = new user({
username: req.body.username,
password: cryptoJs.AES.encrypt(req.body.password, process.env.pass),
});
try {
const savedUser = await newUser.save();
res.status(201).json(savedUser);
} catch (error) {
res.status(500).json(error);
}
});
router.post("/login", async (req, res) => {
try {
const oneUser = await user.findOne({ username: req.body.username });
if (!oneUser) {
res.status(401).json("Wrong credentials");
}
const hp = cryptoJs.AES.decrypt(oneUser.password, process.env.pass);
const password = hp.toString(cryptoJs.enc.Utf8);
if (password !== req.body.password) {
res.status(401).json("Wrong credentials");
}
res.status(200).json(oneUser);
} catch (error) {
res.sendStatus(500).json(error);
}
});
module.exports = router;
//so, there is the code! everything works fine up to the /login section. when I input the right username and password, it gets me the matching user from the database, but when I input the wrong username and the right password immediately after, it says "wrong credentials which is also fine. But when I input the wrong password after all the previous inputs, it brings this error " Cannot set headers after they are sent to the cliententer code here
"
CodePudding user response:
The set header error when will display that you send/return two "res" so use you have to use if-else not if
CodePudding user response:
So the problem is that you send a response to the client, while you already sent a response to the client. When the password is different, you send "Wrong Credentials", but the script will also try to send the oneUser Mongo Object.
To get rid of that, either use an if .. else .. like @Evan proposed, either return the response so you're sure that the script stop there.
The "if/else" solution
if (password !== req.body.password) {
res.status(401).json("Wrong credentials");
}
else {
res.status(200).json(oneUser); // will be sent if the condition before is not completed
}
The "return" solution
if (password !== req.body.password) {
return res.status(401).json("Wrong credentials"); // if the password is different, this will stop the script here
}
res.status(200).json(oneUser);