AJAX requests sent from different origins to AWS S3 may encounter CORS errors on occasion

My current objective is to access publicly available files stored in S3.

The CORS configuration for my S3 setup is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <CORSRule>
        <AllowedOrigin>*</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <AllowedHeader>*</AllowedHeader>
    </CORSRule>
</CORSConfiguration>

My JavaScript code implementation looks like this:

const response = await fetch(url, {
    mode: 'cors',
});

const blob = await response.blob();

The code works most of the time, however, I encounter an error in the console occasionally:

Access to XMLHttpRequest at '' from origin '' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Interestingly, after refreshing the page a few times, or sometimes just once, the error disappears and I can successfully retrieve the response object.

Answer №1

Hey everyone, it's me.

The other day, I was investigating successful and unsuccessful requests in Chrome developer tools. It caught my eye that unsuccessful requests were returning a Status code of: 200 OK (from disk cache), while successful ones had a Status code of: 200 OK.

To resolve this issue, I decided to disable caching by using cache: 'no-cache', which seemed to do the trick.

const response = await fetch(url, {
    method: 'GET',
    mode: 'cors',
    cache: 'no-cache',
    headers: {
        Origin: window.location.origin,
    },
});

Although I'm still puzzled as to why cached requests would encounter CORS problems, at least I found a workaround to address it.


// UPDATE:

It turns out I'm not the only one facing this issue. Check out this post for more information: Cached non CORS response conflicts with new CORS request

Answer №2

It appears that the

<AllowedMethod>Head</AllowedMethod>

tag is missing from your configuration file.

This could be causing the issues you are experiencing.

Ensure that in the Allowed Http Methods section, you have selected Get, Head, Options, and also include Access-Control-Allow-Methods, Access-Control-Allow-Origin, and Origin on your whitelist.

Give that a try!

Best of luck

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

[Vue alert]: Issue with rendering: "TypeError: Unable to access property 'replace' of an undefined value"

I'm currently working on a project similar to HackerNews and encountering the following issue: vue.esm.js?efeb:591 [Vue warn]: Error in render: "TypeError: Cannot read property 'replace' of undefined" found in ---> <Item ...

Scrolling is endless with jCarousel - just press a button to keep moving even when you reach the first or

I seem to be experiencing a problem with jCarousel where, upon starting at the beginning, pressing the left button fails to scroll the carousel. The expected behavior is for the carousel to cycle to the end item when the left button is pressed while the f ...

Refreshing CKFinder Form Field with jQuery

Looking to update the value of an input field .ckfinder-input using CKFinder's pop-up image selector. Everything runs smoothly until attempting to assign the selected image URL to the input field with input.val() = fileUrl, resulting in the error mess ...

Issues with Toggling Visibility in HTML, CSS, and Javascript

Currently, I am working on a website and following a tutorial called "Creating Slideshow using HTML, CSS, and Javascript" by W3Schools. In the project, I want to hide the thumbnail images located at the bottom and the navigation arrows initially and have t ...

Transitioning from Backbone to AngularJS - What challenges can be expected?

Currently I am deep into a large Backbone project (around 8000 lines of JavaScript, not counting external libraries) and I am contemplating making the switch to AngularJS. At the moment, a significant portion of my code deals with DOM manipulation, event ...

Tips for refreshing a specific div element at set intervals using JQuery AJAX?

I need to make updates to a specific div element without refreshing the entire HTML page. The code below currently works, but it reloads the entire HTML page. Additionally, I am working with different layouts where I have separate files for the header, l ...

Retrieving HTML array values using jQuery

Presented below is an array of input boxes. <form> 9 <input type="checkbox" name="date[]" value="9"> 10 <input type="checkbox" name="date[]" value="10"> 11 <input type="checkbox" name="date[]" value="11"> </form> The o ...

Error message: ngRepeat does not allow duplicate elements in an array

Upon review, I discovered this particular piece of code: <!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> <body> <script> var app = angular.module("myS ...

Correctly align the div on the screen as the viewport is scrolled

I am currently working on a parallax website where the sliders are designed to slide from the left and align within the viewport as the user scrolls. However, I have encountered an issue where multiple scroll actions are required for the slide to align pro ...

AngularJS radio buttons can now be selected as multiple options

Currently, I am in the process of learning angular and have implemented a radio button feature in my program. However, I have encountered a perplexing issue that I cannot seem to explain. <!DOCTYPE html> <html> <head> <meta ch ...

After the jquery.show function is executed, an unexpected WebDriverException occurred, indicating an unknown error that prevents focusing

Here is my line of JavaScript code: $('#name').show(); And this is my webdriver code line: wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("name"))).sendKeys("Some Name"); When running the test, I encountered an exception: Web ...

Incorporating Scatter Dots into a Horizontal Stacked Bar Chart using Chart.js

My horizontal stacked bar chart is not displaying pink scatter dots based on the right y axis numbers. I need help figuring out what I am doing wrong. When I change the chart to a normal bar instead of horizontal, the dots appear. However, I require them ...

Elevate state in React to modify classNames of child elements

I have a structured set of data divided into 6 columns representing each level of the hierarchy. When a user makes selections, their chosen location is highlighted with a dynamic CSS class name and displays the relevant data list. I've managed to impl ...

When using Inertia.js with Laravel, a blank page is displayed on mobile devices

Recently, I've been working on a project using Laravel with React and Inertia.js. While everything runs smoothly on my computer and even when served on my network (192.168.x.x), I encountered an issue when trying to access the app on my mobile phone. ...

Issue with hasClass and addClass not working as expected

Why isn't the script below adding a class (.active) to .global-header when .navigation.primary has a class of .active? JS if($(".navigation.primary").hasClass("active")) { $('.global-header').addClass('active'); } HTML < ...

Is it possible to call a REST API in Javascript by passing the username and password as

I have been attempting to use Javascript to call the AwaazDe REST API with a specific username and password, but I'm encountering issues. Below is my code: function authenticateUser(user, password) { var token = user + ":" + password; ...

Running a JAR file on AWS Elastic Beanstalk with Node.js

Currently, I am executing the following code on my Elastic Beanstalk AWS instance using node.js: var exec = require('child_process').exec; var child = exec('java -cp my.jar com.whatever.my.Class -t param1 -u param2'), function (error, ...

Interact with HTML style attribute using JavaScript

Is there a way to retrieve a specific CSS property from the style attribute of an HTML element, without considering the stylesheet or computed properties? For example: <div style="float:right"></div> function fetchStyleValue(element, propert ...

What steps can be taken to ensure that a WebSQL query does not return negative

Here's the code snippet I am currently using: function decrementCart(quantity, id){ db.transaction(function(tx){ tx.executeSql("UPDATE cart SET quantity=(quantity -1) WHERE id=?", [id]) ...

Wordpress Ajax deeplinking leads to a 404 error page

Hey there, This is my first time posting here, and I want to say thank you for all the help I've already received by reading through previous posts. I'm currently working on a WordPress project, but I seem to be struggling to get a clear overvi ...