Default cross-origin behavior of the Fetch API

According to the Fetch Specifications, the default Fetch mode is 'no-cors'.

The specifications state that a request's mode can be "same-origin", "cors", "no-cors", "navigate", or "websocket". Unless otherwise specified, it defaults to "no-cors".

However, I have observed a difference in behavior between using mode: 'no-cors' and not specifying a mode at all. In this JSFiddle example, setting the mode as 'no-cors' makes the response inaccessible to JavaScript, while omitting the mode allows access to the Response object.

Does explicitly stating the fetch mode create a different outcome compared to relying on the default behavior with the same mode internally? What am I overlooking?

Answer №1

By default, the Fetch algorithm uses 'no-cors' as the mode for requests. However, in certain situations specified in the spec, a different mode such as 'cors' is used for cross-origin requests.

For cross-origin requests specifically, the Fetch algorithm sets the response tainting to 'cors' and requires the use of the CORS protocol for fetching.

The Main fetch algorithm's step 12 contains substeps that determine the mode based on various conditions.

↪ The request's current URL origin matches the request's origin and CORS flag is unset
↪ Request's current URL scheme is "data"
↪ Request's mode is "navigate" or "websocket"

  1. Set request's response tainting to "basic".
  2. Return the result of performing a scheme fetch using the request. …

↪ The request's mode is "no-cors"

  1. Set request's response tainting to "opaque".
  2. Return the result of performing a scheme fetch using the request. …

↪ Otherwise

  1. Set request's response tainting to "cors".
  2. Return the result of performing an HTTP fetch using request with CORS flag set.

In summary, if the request URL doesn't match your code's origin, the scheme isn't data, and the mode isn't explicitly set to navigate, websocket, or no-cors, then the request is made using the CORS protocol.

There is a notable difference between setting the mode to 'no-cors' and leaving it unspecified.

Setting mode to 'no-cors' makes the response inaccessible to JavaScript.

This occurs because the specific substep for 'no-cors' mode is executed instead of the generic one.

Not specifying a mode allows the Response object to be accessible.

This happens when the generic substep is reached, triggering a CORS-enabled fetch.

Is there a difference in behavior between specifying the fetch mode and letting it use the default mode?

Yes, explicitly setting the mode to 'no-cors' for a cross-origin request bypasses CORS, while not specifying the mode results in a CORS-enabled fetch.

The statement about the mode defaulting to 'no-cors' unless otherwise specified does not imply that all requests made with fetch() have their mode locked to 'no-cors'.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble closing the phonegap application using the Back Button on an Android device

I've encountered an issue with my code for exiting the application. It works perfectly the first time, but if I navigate to other screens and then return to the screen where I want to close the app, it doesn't work. <script type="text/javascr ...

Display or conceal a div based on checkbox selection

I am trying to implement functionality to show/hide a div when a single checkbox is selected. Currently, it works with "Select all" but I am struggling to make it work with a single checkbox. Below is the code for "Select All": JS: <script language=&a ...

Ensure that the main div remains centered on the page even when the window size is adjusted

Here is the code snippet: <div id="root"> <div id="child1">xxxx</div> <div id="child2">yyyy</div> </div> CSS : #root{ width: 86%; margin: 0 auto; } #root div { width: 50%; float: left; border: ...

Javascript - When I preview my file, it automatically deletes the input file

My form initially looked like this : <form action="assets/php/test.php" method="post" enctype="multipart/form-data"> <input type="hidden" name="MAX_FILE_SIZE" value="1000000" /> ...

Adjust the color of the navbar only after a user scrolls, with a slight delay rather than

My code changes the navbar colors when I scroll (200ms). However, I would like the changes to occur when I am slightly above the next section, not immediately. In other words, what adjustments should I make to change the color in the next section and not ...

What is the best method to retrieve child elements from a class list object?

Seems like I have a similar content class <div class="parentclass"> <div class="childClass"> </div> <div class="childClass"> </div> <div class="childClass"> </d ...

Retrieving information from MongoDB to populate the Redux store

Currently, I have successfully set up my Node API and MongoDB. My next focus is on integrating Redux into my application. Below are some code snippets that I would like to share: The Server Order controller is functioning as expected : const getTotal = as ...

Is it possible to input tab characters in a TextField?

I am working with a multi-line MUI TextField and my objective is to input JSON text. However, I encountered an issue where pressing the tab key causes the component to lose focus and shift to the next element on the page. Is there a way to prevent the ta ...

I must only assign the result to "value" if the condition of the map is true

I am looking to set the variable "value" to only contain the value that meets the condition in the map function const arr= [1,2,3,4,5]; value = arr.map(item => item > 4 && item) console.log(value); The resulting value is currently [false, false, fa ...

Can you explain the distinction between ajaxComplete and beforesend when making an Ajax call with JavaScript?

Can you explain the usage of ajaxComplete and beforesend? What sets them apart from each other? Are there any alternative methods similar to success when making an Ajax call? ...

Adding a component to a slot in Vue.js 3

My Goal I aim to pass the Component into the designated slot. The Inquiry How can I effectively pass the Component into the slot for proper rendering? It works well with strings or plain HTML inputs. Additional Query If direct passing is not feasible, ...

Generating URL parameters for Ajax requests on the fly

My current project involves creating a dynamic form where the number of fields displayed changes based on the user's selection from a dropdown menu. This means that depending on what option they choose, anywhere from 2 to 20 different fields may be sh ...

Using RxJS v5 for Sending a POST Request with Parameters

Snippet of my RxJS code: .mergeMap(action => { const user = store.getState().user; return ajax.post(`${config.API_BASE_URL}/api/v1/rsvps`, { rsvp: { meetup_id: action.payload, user_id: user.id, } }) .map(action => calenda ...

`The steps to retrieve XML response data from an API request`

When using axios to make an API request, how can I receive data in XML format? For example: axios.get(/* URL */).then(response => {/* How do I retrieve the XML data? */}).catch(err => {/* result */}); ...

Issue encountered while using AJAX to load images

Currently, I am utilizing a jQuery plugin to fetch images from Flickr. My aim is to organize these images into 3 columns dynamically as they are loaded, ensuring that each image is placed in the shortest column to achieve close to equal lengths for all col ...

Properties of a child class are unable to be set from the constructor of the parent class

In my current Next.js project, I am utilizing the following code snippet and experiencing an issue where only n1 is logged: class A { // A: Model constructor(source){ Object.keys(source) .forEach(key => { if(!this[key]){ ...

How to temporarily toggle an event on and off using jQuery

Is there a way to control the activation and deactivation of a jQuery event? I currently have this functioning code that runs when the page is ready: $(".panzoom").panzoom({ $zoomIn: $(".zoom-in"), $zoomOut: $(".zoom-out"), $zoomRange: $(".zoo ...

"Is there a way to ensure that jPlayer plays the same song even after a page refresh

I have been working on integrating jPlayer with Ajax to ensure that when the page of my website is refreshed, jPlayer will continue playing its current song seamlessly. I have successfully stored track information and the current track during refresh, ho ...

Ramda Transitioning to a Liberated Style of Programming

Unable to find a suitable resource for this particular issue. I apologize if this question has already been asked, but my attempts to locate the answer have proven fruitless (perhaps due to a lack of effective search methods). I've developed a functi ...

Secure your application with Express.js and MySQL user authentication

Greetings everyone, I've been working on setting up a registration form using express.js and mysql. Unfortunately, it seems like my routes are not functioning correctly as they should. Even when all the required details are filled in correctly, the pr ...