Home > OS >  react - axios - api has been blocked by CORS policy error
react - axios - api has been blocked by CORS policy error

Time:11-14

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

CodePudding user response:

Try with this middleware at the top of your server entry so you don't have to repeat yourself in every route handler, and not miss one of them.

app.use((req, res, next)=>{
   res.header("Access-Control-Allow-Origin", "*");
   next();
  }
);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Is the API written by you. CORS is not a UI error, So the code you have posted here is correct only. CORS is a backend error and it can be fixed from backend itself. In CORS policy you have the give the headers which you want to give the permission to access your API.

So for your code, you must have given access to "/users" but you have not given access to "/register".

During the API deployment, you need to give CORS policy, like I have defined my CORS policy below.

   <base />
    <cors>
        <allowed-origins>
            <origin>*</origin>
        </allowed-origins>
        <allowed-methods>
            <method>GET</method>
            <method>POST</method>
            <method>HEAD</method>
            <method>OPTIONS</method>
            <method>PUT</method>
            <method>DELETE</method>
        </allowed-methods>
        <allowed-headers>
            <header>*</header>
        </allowed-headers>
    </cors>

If you see here "*" is my header section and this means that I am allowing all the headers.

CodePudding user response:

Thanks guys, I solved the problem.

I included the cors middleware in my project and used:

app.use((req, res, next)=>{
  app.options('*', cors())
  next();
 }
);

But this time the user part stopped working, so I added:

res.header("Access-Control-Allow-Origin", "*");

Now it's a bit of a strange solution, but my code is working on both sides.

  • Related