I'm using angular-pdf-viewer for PDF Preview but using PDFJS.getDocument gives no-cors error. How to fix this?


#1

I’m using this library on my Ionic Project I’m using this library on my Ionic Project https://github.com/winkerVSbecks/angular-pdf-viewer

and I correctly integrated the module in to my Ionic

But when trying to load a document using this code

Controller


.controller('EBookCtrl', function($state,$scope, $http,pdfDelegate){

PDFJS.getDocument('http://localhost/books/book.pdf').then(function(pdf_doc) {
    console.log(pdf_doc);
});

I’m getting this errror


Fetch API cannot load http://localhost/books/book.pdf. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' 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.
bluebird.min.js:29 Unhandled rejection Error: Failed to execute 'postMessage' on 'Worker': TypeError: Failed to fetch could not be cloned.
    at MessageHandler.postMessage (http://localhost:8100/js/pdf.js:1393:19)
    at sendStreamRequest (http://localhost:8100/js/pdf.js:1210:14)
    at Object.error (http://localhost:8100/js/pdf.js:1253:9)
    at http://localhost:8100/js/pdf.js:3625:18
    at r (http://localhost:8100/lib/bluebird.min.js:31:9367)
    at i._settlePromiseFromHandler (http://localhost:8100/lib/bluebird.min.js:30:14566)
    at i._settlePromise (http://localhost:8100/lib/bluebird.min.js:30:15369)
    at i._settlePromise0 (http://localhost:8100/lib/bluebird.min.js:30:16070)
    at i._settlePromises (http://localhost:8100/lib/bluebird.min.js:30:17289)
    at r._drainQueue (http://localhost:8100/lib/bluebird.min.js:29:3056)
    at r._drainQueues (http://localhost:8100/lib/bluebird.min.js:29:3117)
    at drainQueues (http://localhost:8100/lib/bluebird.min.js:29:1238)
    at <anonymous>

#2

This issue occurs because you test from within the browser.
Your Ionic app runs on port 8100 and you are accessing the PDF on a server running on port 80.
Since the server on port 80 does not send Access-Control-Allow-Origin headers, the browser will not allow displaying the content from the server at port 80.

If you run the app on a device, you will not have this issue.

To resolve the issue in the browser, you can use a proxy-server or add a CORS-filter to your server at port 80.