I am using fetch() to call a url as follow:
const context = useContext(AuthContext);
const navigate = useNavigate();
const handleSubmit = (event) => {
event.preventDefault();
const data = new FormData(event.currentTarget);
// console.log({
// email: data.get("email"),
// password: data.get("password"),
// });
if (data) {
//TODO: Trigger a mutation or update
fetch("http://localhost:4000/api/user/login", {
method: "POST",
crossDomain: true,
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
"Access-Control-Allow-Origin": "http://localhost:4000",
},
body: JSON.stringify({
email: data.get("email"),
password: data.get("password"),
}),
})
.then((res) => res.json())
.then((result) => {
console.log(result);
if (result.token) {
context.login(result);
navigate("/Home");
}
})
.catch((e) => console.log(e));
} else {
console.log("Login failed.");
}
};
{handleSubmit} is then triggered upon clicking on submit button on the page.
The login controller:
const login = async (req, res, next) => {
function generateToken(user) {
return jwt.sign(
{
id: user.id,
email: user.email,
username: user.username,
},
SECRET_KEY,
{ expiresIn: "1h" }
);
}
const user = await User.findOne({ email });
if (!user) {
console.log("User not found.");
}
const match = bcrypt.compare(password, user.password);
if (!match) {
console.log("Wrong password.");
}
const token = generateToken(user);
return { token };
};
Right now the error thrown is "User not found". I don’t understand why is there no user found as the user with the entered email address exists in my mongodb atlas.
Please provide some guidance. Cheers.
2
Answers
You need to add the following code in your login controller .
And i can see from your comment that when you are submitting the form you are getting nothing back !
I can see that you are returning the token . Instead you have to add the following code if everything goes well.
Or
If everything is fine then you will get a response like this:
One more thing to handle
Why is that ?
Because if you don’t handle this type of errors your app will not respond!
Cause it will stuck in the middleware lifecycle !