I solved the "has been blocked by CORS policy" error, but there is something I don't understand, I added a header to the api part and it works successfully in my login form, but in the register part, my code gives a "has been blocked by CORS policy" error and I don't understand the reason.
error free part
client code
await axios.post(
url + detailsLogin.email).then(function (response) {
console.log("data", response);
if (detailsLogin.email === response.data.email && detailsLogin.password === response.data.password) {
console.log("Logged in!");
setLogined(true);
}
else {
console.log("Details do not match")
setError("Details do not match!" )
}
})
.catch(function (response) {
//handle error
console.log("Details do not match", response)
setError("Details do not match!")
});
};
simple api code
app.post("/users/:email", (req, res) => {
const user = db.find((u) => u.email == req.params.email);
res.header("Access-Control-Allow-Origin", "*");
if (user) {
res.status(200).send(user);
} else {
res.status(404).send({
message: "User is not found..",
});
}
});
wrong part
client code
const body = { email: email, name: name, password: password };
const url = "http://localhost:3002/register";
axios.post(url, body
).then((response) => {
console.log(response);
}, (error) => {
console.log(error);
});
simple api code
app.post("/register", (req, res) => {
res.header("Access-Control-Allow-Origin", "*");
const willSaveData = {
id: new Date().getTime(),
email: req.body.email,
name: req.body.name,
password: req.body.password,
};
db.push(willSaveData);
console.log(willSaveData, "from DB");
res.status(200).send(willSaveData);
});
I also keep getting an error when I try to give the header part to the axios. like this ->
axios.post(url, body,{headers: { 'Content-Type': 'application/json'}}
).then((response) => {
console.log(response);
}, (error) => {
console.log(error);
});
I have the same code in both but the solution doesn't work, I don't know why