-1

The specs of fetch() mentioned using fetch() this way:

fetch("https://pk.example/berlin-calling.json", {mode:"cors"})
  .then(res => {
    if(res.headers.get("content-type") &&
       res.headers.get("content-type").toLowerCase().indexOf("application/json") >= 0) {
      return res.json()
    } else {
      throw new TypeError()
    }
  }).then(processJSON)

This is the first time I see {mode:"cors"} and the specs says the default is: {mode:"no-cors"}, but not using it works well:

Demo: https://codesandbox.io/s/lucid-leaf-y9v25?file=/src/App.js

Why is that we don't use {mode:"cors"} and it still works cross origin?

nonopolarity
  • 146,324
  • 131
  • 460
  • 740

1 Answers1

2

The Fetch API calls the Request constructor internally, and with Request:

mode: The mode you want to use for the request, e.g., cors, no-cors, same-origin, or navigate. The default is cors.

So there's no need to specify { mode: "cors" } with fetch - that's the default.

the specs says the default is: {mode:"no-cors"}

That's only the default for certain resources, excluding Fetch and Request. As MDN says:

For example, when a Request object is created using the Request.Request constructor, the value of the mode property for that Request is set to cors.

However, for requests created other than by the Request.Request constructor, no-cors is typically used as the mode; for example, for embedded resources where the request is initiated from markup, unless the crossorigin attribute is present, the request is in most cases made using the no-cors mode — that is, for the <link> or <script> elements (except when used with modules), or <img>, <audio>, <video>, <object>, <embed>, or <iframe> elements.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • To make things maybe a bit clearer, the internal [`fetch`](https://fetch.spec.whatwg.org/#concept-fetch) operation is called from **many** places, the [`GlobalScope.fetch()`](https://fetch.spec.whatwg.org/#dom-global-fetch) method is just one of these. – Kaiido Mar 23 '21 at 04:43
  • @Kaiido and CertainPerformance, do you know the answer to https://stackoverflow.com/questions/66727673/why-does-javascripts-fetch-not-need-to-check-for-status-code-304 ? – nonopolarity Mar 23 '21 at 04:45