1

I'm using the cors library and have the following settings on my server (running on localhost:8000):

  cors({
    // Allow requests from these origins :: Access-Control-Allow-Origin
    origin: `http://localhost:8001`,

    // Allow certain headers :: Access-Control-Allow-Headers
    allowedHeaders: [
      "Origin",
      "X-Requested-With",
      "Content-Type",
      "Accept",
      "Authorization"
    ],

    // Allows us to send cookies cross origin :: Access-Control-Allow-Credentials
    credentials: true,

    // Allow this method
    methods: "GET"
  });

This works fine when I make a request like this:

fetch('http://localhost:8000/api/test', { method: 'GET', credentials: 'include', mode: 'cors' })

But I get a CORS error in the console when I add headers to the request:

fetch('http://localhost:8000/api/test', { method: 'GET', credentials: 'include', mode: 'cors', headers: { 'Content-Type': 'application/json' })

The Error I'm getting in Chrome is:

Access to fetch at 'http://localhost:8000/api/test' from origin 'http://localhost:8001' 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.

The only difference is that I added a Content-Type header, but I would expect this to work because its in my list of allowedHeaders

Kesupile K
  • 131
  • 1
  • 6

1 Answers1

1
  origin: `http:localhost:3001`,

It seems wrong, back slashes (//) are missing. Otherwise your sample looks good and it works if I create a simple server with your sample.

If it still does not work, you can try to clear the cache. There was an issue in github: https://github.com/expressjs/cors/issues/159