Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
784 views
in Technique[技术] by (71.8m points)

javascript - Access to image blocked by CORS despite 'Access-Control-Allow-Origin: *' from public API

Here is the code from https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image I'm using to grab the image:

let imgURL = obj.primaryImage;
img = new Image();
img.src = imgURL;
img.crossOrigin = "Anonymous";
img.addEventListener("load", imageProcess, false);

function imageProcess() {
   const canvas = document.getElementById('imgCanvas');
   let ctx = canvas.getContext('2d');
   ctx.drawImage(img, 0, 0);
   let imgData = ctx.getImageData(5,5,1,1).data;
}

When I comment out both the .getImageData and the .crossOrigin lines, the image displays. However, as soon as I try to access the image data, the following CORS error appears:

Access to image at 'https://images.metmuseum.org/CRDImages/ad/original/ap53.226.1.jpg' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

If I only comment out the line containing .crossOrigin, the following error appears:

Uncaught DOMException: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data.

Because the Metropolitan Museum's API is public, the 'Access-Control-Allow-Origin' header is set to '*' on both the JSON from which I'm retrieving the link and the image itself.

Any thoughts?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you have control over the domain images.metmuseum.org, you can add this header server-side.

If you don't, browsers will not allow you to do this. Your only option is to write server-side scripts that grab the image for you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...