ng2-pdf-viewer CORS issues

Viewed 8334

I'm developing an Angular application that needs to display PDF files. To achieve this, I'm currenty using the [ng2-pdf-viewer][1] component. The component works fine for files like:

I do however run into CORS-issues with files like:

The error message I receive:

Failed to load htt://frontendmasters.com/assets/resources/lukasruebbelke/better-apps-angular-2-day1.pdf: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'htt://localhost:4200' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

core.es5.js:1020 ERROR Error: Uncaught (in promise): DataCloneError: Failed to execute 'postMessage' on 'Worker': TypeError: Failed to fetch could not be cloned. Error: Failed to execute 'postMessage' on 'Worker': TypeError: Failed to fetch could not be cloned.

My Code

component.html

<pdf-viewer
    [src]="document.url.url"
    [page]="1"
    [original-size]="false"
    style="display: block;">
  </pdf-viewer>

component.ts

document = {
name: 'Angular 2',
description: 'An amazing Angular 2 pdf',
url: {
  url: 'https://frontendmasters.com/assets/resources/lukasruebbelke/better-apps-angular-2-day1.pdf',
  withCredentials: true
  }
}

If you want me to provide any additional information, please let me know.

3 Answers

For those who work with AWS S3, this issu could be solved by configuration of CORS.

  1. Go to AWS Console S3 and then Your Bucket
  2. Go to the Permissions => CORS Configuration
  3. Edit your CORS rules in the CORS configuration editor, for exemple
<CORSConfiguration>
 <CORSRule>
   <AllowedOrigin>*</AllowedOrigin>
   <AllowedMethod>GET</AllowedMethod>
   <MaxAgeSeconds>3000</MaxAgeSeconds>
   <AllowedHeader>*</AllowedHeader>
 </CORSRule>
</CORSConfiguration>

for more infomation https://docs.aws.amazon.com/AmazonS3/latest/dev/cors.html

I wasn't getting this error on local but when I deployed it on server then only I faced this error so I had to configure my nginx settings like this At location /etc/nginx/sites-available/ I edited my configuration file and added

add_header 'Access-Control-Allow-Origin' '*' always;

in location /media media tag just like this

location /media {
        add_header 'Access-Control-Allow-Origin' '*' always;
        autoindex on;
        alias /path/to/my/media/folder/;
    }

Here is the quick fix.

  1. Go to your AWS console.
  2. Open the S3 Bucket.
  3. Click on the "Permissions".
  4. Go to the bottom where it says "Cross-origin resource sharing (CORS)".
  5. Click on the Edit button top right.
  6. Paste the below JSON in that and save it.
[
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "GET",
            "POST",
            "DELETE"
        ],
        "AllowedOrigins": [
            "*"
        ],
        "ExposeHeaders": [],
        "MaxAgeSeconds": 3000
    }
]
Related