Ad

Express JS Cors Middleware Does Not Work When Server Is Accessed Though Fetch Request

- 1 answer

Server is on http://localhost:3001, and client is same, but with port 3000.

On client I run simple fetch, I need to get logged-in user data from server, and currently I am doing it just using GET method(GET, POST, none work) like this(I also have to include cookies):

fetch("http://localhost:3001/user", {
      method: "GET",
      credentials: "include",
      headers: {
        "Content-Type": "application/json"
      }
    }).then(response => {
      console.log(response);
    });

And the server:

const cors = require("cors");
var corsOptions = {
  origin: "http://localhost:3000",
  optionsSuccessStatus: 200
};
app.get("/user", cors(corsOptions), function(req, res, next) {
  u_session = req.session;
  const db_result = db
    .collection("users")
    .findOne({ email: u_session.email }, function(err, result) {
      if (err) throw err;

      res.json({ email: result.email, type: result.type });
    });
});

What I get is cors error:

Access to fetch at 'http://localhost:3001/user' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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.

Also if i go to server URL through browser, I can see access-allow-control-allow-origin header set successfully.

sample

Also as requested, screenshot of failed case network tab: enter image description here

I've searched plenty of solutions on the internet, nothing seems to work. Am I missing something?

Thanks for any help.

Ad

Answer

Ensure that if you have a proxy set that it is set to http://localhost:3001. After that adjust your fetch to only use a partial url like so:

fetch("/user", {
      method: "GET",
      headers: {
        "Content-Type": "application/json"
      }
    }).then(response => {
      console.log(response);
    });

it should be safe to remove this as well:

const cors = require("cors");
var corsOptions = {
  origin: "http://localhost:3000",
  optionsSuccessStatus: 200
};
Ad
source: stackoverflow.com
Ad