Troubleshooting the intermittent issues of JavaScript image setting with S3 CORS

While experimenting with the canvas element to save images, I encountered issues specifically in Chrome related to setting the initial image.

<a href="#" data-src="https://s3.amazonaws.com/imphotos/uploads/thumb_IM_17592186048618_17592186048643.jpg">ONE</a>
<a href="#" data-src="https://s3.amazonaws.com/imphotos/uploads/thumb_IM_17592186047657_17592186047769.jpg">TWO</a>
<a href="#" data-src="https://s3.amazonaws.com/imphotos/uploads/thumb_IM_17592186047657_17592186047727.jpg">THREE</a>

  var setImg = function(src){
    var img = new Image;
    img.crossOrigin = "Anonymous";
    img.onload = function(){
      alert("LOADED!");
    }
    img.onerror = function(){
      alert("ERROR!");
    }
    img.src = src;
  };

  $(document).ready(function(){
    $("a").click(function(e){
      var src = $(e.currentTarget).data('src');
      setImg(src);

    });
  });

Initially, this process works smoothly, but subsequent attempts to load second or third images fail due to CORS settings, despite having the following CORS configuration:

<CORSRule>  
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedHeader>*</AllowedHeader>
    <AllowedMethod>GET</AllowedMethod>
</CORSRule>

Upon constructing a new image through a click handler, an error message is received:

Image from origin '' has been blocked from loading by Cross-Origin Resource Sharing policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

This issue does not occur initially and seems to be specific to Chrome as it works fine in Firefox.

UPDATE:

Further investigation revealed that the image loading issue was not dependent on the order of execution but rather random.

A JS fiddle was created for better understanding, showing that some pictures in the S3 bucket work while others do not. Do I need to apply CORS settings retroactively to all images in the bucket? Could this be an S3 bug or an issue with my images themselves?

Clicking on "TWO" triggers a loading alert, but only 1 out of 3 images loads successfully, with the others throwing the CORS error.

https://jsfiddle.net/6L44ttus/

Update 2:

Considering the suggestion to switch the bucket name format (e.g., my-bucket.s3 instead of s3.my-bucket), I tested this change but unfortunately, none of the images are loading now.

https://jsfiddle.net/6L44ttus/3/

Answer №1

element, I discovered the root cause of my issue. It turns out that I was fetching images from my localhost using HTTP while trying to access assets via HTTPS. UPDATE* Upon further investigation, I realized that this explanation is not accurate. After encountering some misleading results, I ultimately resolved the issue by configuring an nginx proxy with the appropriate headers.

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

Allow React to complete one loop (including setState) before starting another loop

handleSubmit = () => { this.setState({ modalState: false }) this.state.codeToClass.forEach((code, classId, map) => { const cr = _.find(this.state.classRoles, { id: classId }) if (code === cr.classCode) { console.log(&apo ...

Could using an image defer script instead of a lazy image script result in an undefined offset error?

To enhance the pagespeed of my website, Pagespeed Insight recommends using deferred images instead of lazy jQuery images. In an effort to follow this advice, I made adjustments based on suggestions from another source. Read more on stackoverflow I utiliz ...

Looping through ng-repeats, extracting checked checkbox values in Angular

I am currently dealing with multiple nested ng-repeats in my project, and the third level down consists of a group of checkboxes. Initially, I receive an array of options for these checkboxes, which I handle with the following code snippet: <div class= ...

Javascript cards arranged in descending order

I'm in the process of developing a sorting feature that arranges cards in the DOM from Z to A with the click of a button. Although I've successfully implemented the logic for sorting the array, I'm facing difficulties in rendering it. Withi ...

Tips for applying consistent border textures to varying sized rectangles without distorting the corners

This is a request about textures. I am interested in having a variety of rectangles with different aspect ratios. When I apply a texture https://i.sstatic.net/Yq9nZ.png If I place the texture on a Plane, it gets distorted, especially at the corners. (Th ...

Utilizing Arrays for Angular Data Binding with AJAX

I am currently experimenting with loading Ajax data into an array and then binding the array using Angular. Here is my code (I have some experience with KO, so I'm keeping it simple for now): Update: I managed to get it working. I believe the issue w ...

Generate two arrays in JavaScript using the information stored in an object

I am in need of a loop that can generate 2 arrays based on some data... To start, I create the following 2 arrays: namelist = []; countList = []; { "id": "665", "name": "primary", "contents": { "692": { "id": "692", ...

The Django and Ajax like button is functioning properly, but it seems to only work on the first item

Hey there, I'm having an issue with my like button. It seems to be working only on the first item and not functioning on the rest. Here is a snippet from my views.py: @login_required @require_POST def like(request): if request.method == 'PO ...

Transforming PHP Arrays into JavaScript Objects

I am facing some challenges with my code due to my limited understanding of JSON and JS. Here's the code snippet I have been working on: $markersData = array(); $x = 0; while ($row = @mysqli_fetch_assoc($result)) { $type = $row['type']; ...

Executing two nested loops with a delay in jQuery

I am currently working on a script that sends an ajax post to another page. I need to run two for loops before sending the ajax request with a timeout. The first loop is successful, but when I try to run the second loop, all requests are sent at the same ...

Tips for consolidating multiple strings into one string using jQuery

<span class='st_twitter_large' displayText='Tweet'></span> <span class='st_linkedin_large' displayText='LinkedIn'></span> <span class='st_facebook_large' displayText='Faceboo ...

Simple steps to validate an ajax response with a specific string

I'm encountering a problem with a simple ajax call that involves checking the returned text against a string: // in my php file echo 'mystring'; // in my javascript if((request.readyState == 4) && (request.status == 200)){ if(req ...

Why is Joi validation triggering an error when dealing with a nested object? Could this issue be connected to the use of dot notation in the

I am facing an issue with my joi validation when trying to submit a form. The error message I receive is: STACK: Error: "author.surname" is not allowed at module.exports.citationJoi Upon reviewing my joiSchema, everything seems correct: const n ...

Encountering issues when making API calls from a .NET program

I'm encountering an error when trying to call an API from a .NET application: "Script7002:XMLhttpREQUEST:Network Error 0x80070005, Access Denied." Interestingly, I am able to get the correct response when testing the API with the "Advanced Rest Cl ...

Assign a class when a path is clicked using Leaflet.js

My goal is to apply a specific class to the clicked polygon by using the following code: function addClass() { function style(feature) { return { className: "active" }; } } function onEachFeature(feature, layer) { ...

Efficiently update a multi-step form using Ajax and jQuery by adding new content without needing to reload the

Is it possible to create a multistep form on a single page without reloading the div with content from a PHP file, but instead appending it below? Here is my current progress: $(document).on('submit', '#reg-form', function(){ var ln = ...

Concealing categories within an accordion-styled menu

Recently, I put together a list that includes various pieces of information along with an accordion menu. Take a look at the list However, I've encountered a small issue which has left me quite perplexed. When a menu item is clicked - for instance, ...

How can I enable step-by-step functionality in Vue.js?

I am trying to set the default option to: Additional Info, instead of: Personal details I have looked everywhere for documentation on this but cannot find any. Can someone please assist me with this? Thank you. https://jsfiddle.net/bt5dhqtf/98/ <div i ...

Triggering a 'RegisterStartupScript' call resulted in an 'Object expected' error

Something strange is happening here. Let me explain the situation: I have a page with a usercontrol used for popups. This usercontrol has a placeholder where I can load any other usercontrol dynamically inside the popup. Everything works smoothly thanks ...

Incorporating HTML coding into SharePoint Online

Can HTML codes be added to SharePoint Online? I am interested in adding an HTML code from Statista, like the one below: <a href="https://www.statista.com/statistics/262861/uk-brent-crude-oil-monthly-price-development/" rel="nofollow"><img src=" ...