Rahul Kumar
Rahul Kumar

Reputation: 1

No 'Access-Control-Allow-Origin' header is present on the requested resource while using htmlToImage

I am trying to use htmlToImage method but is is showing error "Access to fetch at " / aws image url / " from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled."

The image url which I am using in img tag, is coming from aws s3 bucket. And on AWS s3 we have already configured CORS

  1. AllowedOrigins as "*".
  2. AllowedHeaders as "*".

Note:

  1. This is working fine in firefox browser but not working in chrome browser and Opera browser.
  2. When I am opening genrated base64 in browser tab, the image is not coming. only blank is coming.

My html code is :

<div id="editedimage">
   <img class="img-style" src="<imgUrl>" alt="image"> 
<div>

And js code is :

    var node = document.getElementById('editedimage');
    htmlToImage.toPng(node)
      .then((dataUrl) => {
        console.log("url", dataUrl);
      .catch((error) => {
      console.error("error", error);
      });

Team, Help me out. Thanks in advance.

Upvotes: 0

Views: 668

Answers (2)

Chouffiboy
Chouffiboy

Reputation: 26

I had the same issue trying to use htmlToImage.toPng() (v1.11.3) on a node containing an image loaded from AWS S3 Bucket, with the same CORS policy as you on my bucket.

Adding the attibute 'crossOrigin="anonymous"' on my element worked just fine for me so I would update your element like that:

<div id="editedimage">
   <img class="img-style" src="<imgUrl>" alt="image" crossOrigin="anonymous"> 
<div>

Upvotes: 1

Arash Hatami
Arash Hatami

Reputation: 522

If you want to display base 64 image you need to sanitize the url before using it in template.

import { DomSanitizer } from '@angular/platform-browser';

constructor( private sanitizer: DomSanitizer, .... ) {
    this.displayImage = this.sanitizer.bypassSecurityTrustUrl("data:Image/*;base64,"+imageData);
}

Upvotes: 1

Related Questions