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

Karma, Webpack, and AngularJS are successfully passing all tests, yet encountering karma errors with an exit code of 1

Currently running karma 4.0.1, webpack 4.31.0, angular 1.6.8, karma-jasmine 2.0.1, jasmine-core 3.4.0 Recently at my workplace, I transitioned our angularjs application from a traditional gulp build process to webpack + es6. The journey has been smooth wi ...

The dilemma between installing Electron or installing Electron-Builder: which one

When it comes to installing Electron for an Electron app with React, the method can vary depending on the tutorial. Some tutorials use electron-builder while others do not, but there is little explanation as to why. First: npx create-react-app app cd app ...

Update the text on a button using a different button

function modify_button_text(){ //update the word from cat to dog. } <button id="button_1_id" >Cat</button> <br><br><br><br> <button id="modify_button_text_btn" >Change the Text of Above Button</button> ...

Client component in Next.js is automatically updated upon successful login

I am currently working on a Next.js + DRF website that requires authentication. I have set up my navbar to display either a "log in" or "log out" button based on a boolean prop passed from the server side to the client-side: export default async function R ...

Creating registration and login forms using an express server

Currently, I'm in the process of creating a basic website on my localhost that incorporates a signup form along with other essential HTML elements. The setup for the signup procedure went smoothly as planned. When a user completes the form and submits ...

Error: The 'replace' property of null cannot be read in select2

In my Node Express app, I am incorporating select2, and encountering an error when supplying an array as the data source with data: dataBase. The issue arises as Uncaught TypeError: Cannot read property 'replace' of null. Although using an ajax ...

Remove the class upon clicking

I recently created a toggle-menu for my website that includes some cool effects on the hamburger menu icon. The issue I am facing is that I added a JavaScript function to add a "close" class when clicking on the menu icon, transforming it into an "X". Whil ...

Developing a Rails application integrated with Pusher or Faye for real

I've been tasked with creating an app similar to this: I'm facing challenges in updating the bids. I am considering using technologies like Pusher or Faye ( or ) and subscribing to each event. However, I'm wondering if there is a more elega ...

Can you explain the execution process of this Http.post method and provide details about the code path it follows

As I delve into the world of web development, one aspect that has me stumped is the functionality of the Http.post section within a project I stumbled upon on GitHub. Specifically, this pertains to an ExpressJS with Typescript repository I came across. So, ...

Showcasing the time variance using javascript/jquery

I am currently using a datepicker to select dates, with the intention of calculating the difference between the chosen dates and then displaying an alert with the calculated difference. Unfortunately, I am encountering issues with getting the code to work ...

Showing XML content with JavaScript

Trying to parse a simple XML list using JavaScript, but having trouble formatting it the way I need. <TOURS> <MONTH> <TOUR> <NUMBER>1</NUMBER> <VENUE>City Name - Venue Name</VENUE> < ...

Error encountered while making a REST API call in Ajax: Unforeseen SyntaxError: Colon unexpected

I am currently troubleshooting my code to interact with a REST API. My platform of choice is "EspoCRM" and I aim to utilize its API functionalities. The official documentation recommends using Basic Authentication in this format: "Authorization: Basic " ...

What is the best way to customize the CSS of the Skype contact me button?

I am struggling with customizing the Skype contact me button. The standard Skype button has a margin of 24px and vertical-align set to -30px. I have tried removing these styles but have had no success. Here is the code snippet I am working with: Skype ...

"Encountering an error in Vue3 CompositionAPI: 'quizz is not defined' while trying to call a function from the

When attempting to call a function, I am encountering an error that says "Uncaught ReferenceError: quizz is not defined." <script setup> import { defineProps } from "vue"; import { useRouter } from "vue-router"; const router = us ...

"Debugging a simple demonstration showcasing NodeJS, AngularJS, and Express

Currently, I am following an online tutorial to learn a new concept. I have reached the part where I need to display data using HTTP GET from the controller, while the sample data is stored in the server file. I managed to fetch the data from the controlle ...

What is the best way to import and export modules in Node.js when the module names and directories are given as strings?

Here is the structure of my folder: modules module-and index.js module-not index.js module-or index.js module-xor index.js moduleBundler.js The file I'm currently working on, moduleBundler.js, is re ...

What are the steps to create a class diagram for a NodeJS application?

For my final year project, I am looking to develop an application using Node API. As we delve into drawing the class diagram, it occurs to me that unlike Java or C#, Node JS does not have a built-in class concept. What would be the most effective approac ...

Tips for automating the execution of Chrome extension code on pages with infinite scrolling

Creating my debut Chrome extension, I'm developing a tool to substitute text on web pages. The current code effectively operates on content loaded by DOMContentLoaded. However, when pages employ infinite scrolling and new content is added, the text r ...

When you use Array.push, it creates a copy that duplicates all nested elements,

Situation Currently, I am developing a web application using Typescript/Angular2 RC1. In my project, I have two classes - Class1 and Class2. Class1 is an Angular2 service with a variable myVar = [obj1, obj2, obj3]. On the other hand, Class2 is an Angular2 ...

Eliminate the prefixes of object keys in Node.js

This is my first time reaching out for help on a forum. I've been struggling with an issue for days and haven't been able to find a solution. It all started with a database query that returned the following data: { "prod_format": "400 ml", "pro ...