MegaMatt
MegaMatt

Reputation: 23763

Why is my simple fetch triggering a CORS error?

I am attempting to perform a simple fetch to a server I do not control:

fetch('https://path.to.the.server/api/items');

This is a GET endpoint. Using Firefox 52.9.0, if I paste my fetch code into the console and hit Enter, I see the GET request fail in the Network tab with a 401. And in the console, I receive the following errors:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://path.to.the.server/api/items. (Reason: CORS header 'Access-Control-Allow-Origin' missing).

TypeError: NetworkError when attempting to fetch resource.

There's nothing here in this fetch that should be triggering CORS. Importantly, I do not see a preflight OPTIONS request in the Network tab prior to the 401. The 401 failure is on the GET request itself. However, the errors in the console still point to the browser being denied due to CORS.

So I'm confused why CORS is an issue here. This should be a simple fetch. Is there something I'm missing?

Note: This project is in an "offline" environment, which is why I have not linked the actual URL for community testing.

Upvotes: 2

Views: 3106

Answers (2)

Advena
Advena

Reputation: 2233

The mode in fetch determines how CORS is managed for a certain request when the resource being requested is from a different origin. The possible modes are "cors", "no-cors" and "same-origin", with "cors" being the default mode (1).

Therefore, even a "simple request" with fetch triggers the CORS protocol.

Setting mode to "no-cors" solves this, but be aware that with "no-cors"(1):

  • prevents JavaScript from reading the response
  • is useful for resources that don't have to be processed with JavaScript, like those that need to be cached or embedded as elements (<img/> or <iframe/>) on the webpage (1, 2)
  • requests are still made and responses are still received

More about this in this StackOverflow answer from @sideshowbarker♦

Upvotes: 2

dave
dave

Reputation: 64657

why I'm getting CORS-related errors when this is not a request that requires validation against CORS.

Even if a request doesn't need a preflight CORS check, it will still get a CORS check.

For example, if you run in the console

var xhr = new XMLHttpRequest;
xhr.open("GET", "https://www.mozilla.org/en-US/");
xhr.send();

in the network tab, you will be able to click into "Response" and see the response, but you will still get

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.mozilla.org/en-US/. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

The reason there is no pre-flight is because a GET request isn't supposed to modify anything, whereas other types of requests do, so the browser first does a "safe" check, before even allowing the real request to hit the server.

Upvotes: 3

Related Questions