解決pdf.js不支持跨域問題


解決跨域問題

首先直接打開任何一個鏈接pdf文件是不存在跨域問題的,正是因為pdf.js需要通過ajax以文件流的形式去解析才造成了跨域問題。

當pdf.js從 http://localhost 請求 http://localhost:8081/files/demo.pdf , 很遺憾啊,pdf.js發出了個警告:

file origin does not match viewer's

因為當前源與目標源不一樣,pdf.js直接攔截了。

解決方法一(代理方式):

在http://localhost 服務器配置代理,nginx如下:

location /files {
  proxy_pass http://localhost:8081/;
}

使用方法,不要帶上前綴

http://localhost/pdf.js/web/viewer.html?file=/demo.pdf

這種方法有缺點:

1、不能使用完整鏈接,如:http://localhost:8081/files/demo.pdf

2、如果目標存在多個目錄需要增加配置,如: /files/demo.pdf 、 /pdf/demo.pdf


解決方法二(配置CORS跨域):

在目標服務器 http://localhost:8081 新增下面頭部即可。

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS
Access-Control-Expose-Headers: Accept-Ranges, Content-Encoding, Content-Length, Content-Range

nginx(其他服務器類似):

location / {
  add_header Access-Control-Allow-Origin '*'; add_header Access-Control-Allow-Methods 'GET, POST, PUT, OPTIONS'; add_header Access-Control-Expose-Headers 'Accept-Ranges, Content-Encoding, Content-Length, Content-Range'; } 

使用方法:

http://localhost/pdf.js/web/viewer.html?file=http://localhost:8081/demo.pdf

以為這樣就大功告成了嗎? 很遺憾,還是報了之前的錯誤

file origin does not match viewer's

翻了翻官方文檔,然而沒有找到解決方案。但是並不能主檔我前進,現在只好從源碼入手。

在viewer.js文件里搜索關鍵字 (file origin does not match),哈哈真的有 (本來就有的好嗎)。

貼下關鍵代碼, 在1863行左右:

{
  var HOSTED_VIEWER_ORIGINS = ['null', 'http://mozilla.github.io', 'https://mozilla.github.io']; validateFileURL = function validateFileURL(file) { if (file === undefined) { return; } try { var viewerOrigin = new URL(window.location.href).origin || 'null'; if (HOSTED_VIEWER_ORIGINS.indexOf(viewerOrigin) >= 0) { return; } var fileOrigin = new URL(file, window.location.href).origin; if (fileOrigin !== viewerOrigin) { throw new Error('file origin does not match viewer\'s'); } } catch (ex) { var message = ex && ex.message; PDFViewerApplication.l10n.get('loading_error', null, 'An error occurred while loading the PDF.').then(function (loadingErrorMessage) { PDFViewerApplication.error(loadingErrorMessage, { message: message }); }); throw ex; } }; } 

這里使用了try捕捉錯誤,注意第2個條件語句,因為當前源與目標源不一樣,所以拋出了異常。

if (fileOrigin !== viewerOrigin) {
//  throw new Error('file origin does not match viewer\'s');
}

很好解決,只要把throw這行注釋即可。 這就到此結束了,完美解決跨域問題。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM