Skip to content
Advertisement

cors error even after allowing all origins *

i have a post request on my at http://localhost:3000 and request resources from http://localhost:5500 even after allowing all origins it gives error. I’m stuck on this for a few hours now please help.

i get this error

Access to fetch at 'http://localhost:3000/upload' from origin 'http://localhost:5500' has been blocked
by CORS policy:
Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

this is where i’m setting my header

app.all("*", (req, res, next) => {
  // CORS headers
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");
  res.header("Access-Control-Allow-Credentials", "true");
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept, Key, Authorization , client-security-token"
  );
  next();
});

this is my fetch request

 const resp = await fetch("http://localhost:3000/upload", {
          method: "POST",
          headers: {
            Authorization: `Bearer ${localStorage.getItem("access_token")}`,
            accept: "application/json",
          },
          body: formData,
        });
        const data = await resp.json();
        console.log(data);

Advertisement

Answer

Try below.

Added a condition to check if the request type is OPTIONS and then return response with status 200.

app.all("*", (req, res, next) => {
  // CORS headers
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");
  res.header("Access-Control-Allow-Credentials", "true");
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept, Key, Authorization , client-security-token"
  );
  if (req.method === "OPTIONS") {
      return res.status(200).end();
  }
  
  next();
});

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement