'image url showing cors error in angular but working fine javascript
we have used aws s3 for image storing. When we tried convert image to base64. code working fine javascript but code is not angular
javascript code:
function getBase64Image(imgUrl, callback) {
var img = new Image();
// onload fires when the image is fully loadded, and has width and height
img.onload = function(){
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png"),
dataURL = dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
callback(dataURL); // the base64 string
};
// set attributes and src
img.setAttribute('crossOrigin', 'anonymous'); //
img.src = imgUrl;
}
this.getBase64Image("imageURL", function(base64image){
console.log(base64image);
});
It is working fine in javascript but angular throws below error
Access to image at 'https://examplecros.s3.us-east-2.amazonaws.com/images5.jpg' from origin 'http//localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
5.jpg:1
Failed to load resource: net::ERR_FAILED
Solution 1:[1]
AWS S3 and your local are 2 different domains and you have already consider to set its corresponding property:
img.crossOrigin = 'Anonymous'.
Also, you have to config cross domain setting in your backend by this syntax:
CORS_ORIGIN_ALLOW_ALL = True.
If the problem exist yet, try adding a random parameter to your image URL to avoid your app getting the img from local cache:
img.src = imgUrl + '?r=' + Math.floor(Math.random()*100000);
I used the above steps and solved my problem witch was similar to yours.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kamal24h |
