I'm feeling completely lost trying to understand cors in conjunction with fetch, particularly when an options request is

I am using whatwg fetch in the code snippet below:

  const headers = new Headers();

  //uncommenting this causes the preflight options request to be sent 
  //headers.append('x-something', 'foo');

  const response = await fetch('http://localhost:5000/api/managers', {
    headers,
    credentials: 'include'
  });

The commented line is necessary for triggering a preflight options request:

 //headers.append('x-something', 'foo');

To allow the localhost request, the server configuration includes this:

app.use(cors({
  origin: 'http://localhost:4040'
}));

If I include credentials: 'include', Chrome displays an error:

Fetch API cannot load http://localhost:5000/api/managers. Credentials flag is 'true', but the 'Access-Control-Allow-Credentials' header is ''. It must be 'true' to allow credentials. Origin 'http://localhost:4040' is therefore not allowed access.

Removing credentials: 'include' and including the custom header results in an OPTIONS request with a 204 No Content response:

  headers.append('x-something', 'foo');

  const response = await fetch('http://localhost:5000/api/managers', {
    headers
  });

Simply making the code as follows displays a GET request with a JSON response:

  const response = await fetch('http://localhost:5000/api/managers', {
  });

Answer №1

The error message you received indicates that your server requires the response header

Access-Control-Allow-Credentials: true
. You can find more information about this in the Fetch documentation:

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

What is the method for including an inner wrapper around an element in Angular?

Is there a way to create an Angular directive that adds an inner wrapper to a DOM element without replacing the inner content? I have tried implementing one, but it seems to be replacing instead of wrapping the content. (view example) Here is the HTML sni ...

WebDriverIO effortlessly converts the text extracted using the getText() command

One of my webpage elements contains the following text: <span class="mat-button-wrapper">Sicherheitsfrage ändern</span> However, when I attempt to verify this text using webdriver, it indicates that it is incorrect assert.strictEqual($(.mat ...

Reacting with Node.js: Capturing a selected option from a dropdown menu and storing it in the database

On my React frontend, I have a select dropdown like this: <select name="level" value={level} onChange={this.handleChange} className="form-control"> <option>Begineer</option> <option>Intermediate</option> <option> ...

Resolving Null DateTime Property in MVC Model Through Ajax Post

While working on an ajax POST request with Model, everything seemed to be functioning well except for one datetime property. Upon inspecting the network tab in the browser, I noticed that all values were being passed in the request payload as expected. How ...

Change the term to its corresponding translation

I have developed an Ionic Multilingual App that includes a select feature. Within this select, choosing a specific option disables certain page elements. However, I am facing an issue where one of the elements needs to change its text based on the selected ...

Python / Selenium - Comments in the code may be playing a significant role in causing the NoSuchElementException to be triggered

Currently working on streamlining tasks at work by eliminating mundane activities. Here is an example of using Python's Selenium library to access a website that contains registers of German companies. The script performs the following actions: Open ...

Is there a way to run a node script from any location in the command line similar to how Angular's "

Currently, I am developing a node module that performs certain functions. I want to create a command similar to Angular's ng command. However, I am facing compatibility issues with Windows and Linux operating systems. Despite my attempts to modify the ...

Looking to develop a dynamic password verification form control?

I am in the process of developing a material password confirmation component that can be seamlessly integrated with Angular Reactive Forms. This will allow the same component to be utilized in both Registration and Password Reset forms. If you would like ...

The $.each function seems to be stuck and not cycling through the

Dealing with a rather intricate JSON structure, I'm encountering difficulty iterating through it using the $.each() function. It seems to be related to the unusual 2-dimensional array passed in the value section of the standard array (hopefully that m ...

Update JSON values using JavaScript or jQuery

In the code snippet provided, there is an issue where nameElem.data('index') does not change, causing it to always display element 1 in the list. I attempted to change the json value with cardInfo[i].data.index = index;, but that did not solve th ...

Tips for establishing communication between a React Native webView and a React web application

I am currently working on establishing communication between a webView in react-native and a web-app created with React-360 (and React). I am utilizing the react-native-webview library and following a guide for creating this communication. You can find the ...

Retrieving information from a PHP script with the help of the $.get method

I need to retrieve data from a PHP script that is functioning correctly. $.post( "http://labs.*********.com/inc/ajax/till_status.php", { id:$("#potentialID").val() } ).done( function (data) { currentTillStatus = data; }); The ...

Automatically refreshing the canvas whenever the value of an HTML element is modified in Javascript

Below is the javascript code that is relevant <script> $.fn.ready(function() { var source = $('#source').val(); Meme('url1', 'canvas','',''); $('#top-line, #bottom-li ...

The console is displaying an undefined error for _co.photo, but the code is functioning properly without any issues

I am facing an issue with an Angular component. When I create my component with a selector, it functions as expected: it executes the httpget and renders a photo with a title. However, I am receiving two errors in the console: ERROR TypeError: "_co.photo ...

Removing a Dom element using stage.removeChild( )

When the number 6 is typed and entered into the game, the function correct() in the code snippet below determines what action to take. I would like to remove the DOM element gg (the equation 3+3=input) from the stage after typing 6 and pressing enter. How ...

Failure of AJAX HTML function to retrieve value from textarea

I am displaying data in the first three columns of a table, with the last column reserved for user feedback/comments. However, when the form is submitted, the values in the textarea are not being posted. The table has 6 rows. The Sample TR: <tr> &l ...

The utilization of conditional expression necessitates the inclusion of all three expressions at the conclusion

<div *ngFor="let f of layout?.photoframes; let i = index" [attr.data-index]="i"> <input type="number" [(ngModel)]="f.x" [style.border-color]="(selectedObject===f) ? 'red'" /> </div> An error is triggered by the conditional ...

What is the best way to retrieve the directory path from a FileReader in Java

Hey there, check out these codes I have for reading the file that the user uploads: function readURL(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function(e) { $('#myImg' ...

How can we transfer a jQuery value from an input field without using a single

This task may seem challenging. How can single quotes be eliminated from a variable when passed directly to another variable? I am using jQuery variable $("#test").val() to extract the value from an input below <input type="text" ...

Issue with retrieving date from MySQL column being a day behind in JavaScript (Node.js)

I currently have a Node.js server up and running as the API server for a service that I am developing for a company. The dates stored in the MySQL server that it connects to are related to event start times. Insertion of these dates is flawless, and when ...