I was using mongodb and I migrated to objection and knex for some reasons, And my issue comes from this login code (back server) :
User.query()
.where("email", "=", req.body.email)
.then((user) => {
if (user.length == 0) {
return res.json("Incorrect Email.").sendStatus(401); // If the email is not already recorded
}
I get this error message : Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client And the response I get from the front side is 200. So I think objection.js automatically sends a 200 response, even if the email is incorrect. Anyone facing the same issue ?
EDIT : The front fetch code :
async function handleSubmit(e) {
e.preventDefault();
await fetch(`https://localhost:8443/api/auth/login`, {
method: "POST",
mode: "cors",
credentials: "include",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({ email, password }),
}).then((response) =>
response
.json()
.then(({ data }) => {
console.log(response);
switch (response.status) {
case 200:
localStorage.setItem("xsrfToken", JSON.stringify(data.xsrfToken));
const roles = data.roles;
const _id = data._id;
const accessToken = data.accessToken;
setAuth({ _id, email, password, roles, accessToken });
setEmail("");
setPassword("");
// Remove the console.log before deployment
console.log(data);
navigate(from, { replace: true });
break;
case 401:
setErrMsg("Your Email or your password is wrong.");
errRef.current.focus();
// Remove the console.log before deployment
console.log(data);
break;
case 500:
setErrMsg("500");
console.log(data);
break;
default:
}
})
.catch((error) => {
errRef.current.focus();
console.log(error);
})
);
}
I solved the problem by doing: res.status(401).json("Incorrect Email."); Instead of : res.json("Incorrect Email.").sendStatus(401); And I can't explain why this code worked very well before objection.js.
If anyone can explain it...