简体   繁体   中英

No 'Access-Control-Allow-Origin' header is present on the requested resource. Node Express Fetch

I know that many people experienced very similar problems but fixes that worked for them didn't do anything for me. Whatever I do I get:

Access to fetch at 'http://localhost:5000/api/places/comments/test' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I am using node with express and here is my app.js file (part relevant to CORS):

const app = express();
app.use(bodyParser.json());
app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept, Authorization"
  );
  res.setHeader(
    "Access-Control-Allow-Methods",
    "GET, POST, PATCH, DELETE, PUT"
  );
  next();
});
app.use("/api/places", placesRouter);

Then route file (relevent for route that is not working)

placesRouter.post("/comments/test", requireLogin, addComment);

And finally the handler:

  const addCommentHandler = async () => {
    try {
      const response = await fetch(
        `${process.env.REACT_APP_BACKEND_URL}/api/places/comments/test`,
        {
          method: "POST",
          body: { comment: formState.inputs.comment.value },
          headers: {
            Authorization: `Bearer ${auth.token}`,
            "Content-Type": "application/json",
          },
        }
      );
      const responseData = await response.json();
      console.log(responseData);
    } catch (e) {}
  };

I know for a fact that body is sent and I have also tried in in Postman and it works.

What am I doing wrong here?

You are doing res.setHeader() instead of req.setHeader() !

const app = express();
app.use((req, res, next) => {
  req.setHeader("Access-Control-Allow-Origin", "*");
  req.setHeader(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept, Authorization"
  );
  req.setHeader(
    "Access-Control-Allow-Methods",
    "GET, POST, PATCH, DELETE, PUT"
  );
  next();
});
app.use(bodyParser.json());
app.use("/api/places", placesRouter);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM