PDF.js CORS 问题

新手上路,请多包涵

我遇到 PDF.js 和 CORS 配置问题。

从域 A,我将 PDF.js 加载到一个 iframe 中,其中包含一个文件作为参数(服务器的完整路径,它将返回一个 pdf 文档)。 PDF.js 将使用 origin: domain A 创建对域 B 中服务器的请求。域 B 的服务器返回标题为 Access-Control-Allow-Origin: domain A 的 pdf 文档,到目前为止一切顺利。

在我的网络选项卡中,我看到对服务器的请求,它返回 200 状态正常,但 PDF.js 抛出错误 Unexpected server response (0) while retrieving PDF <url>

问题是,这里发生了什么,CORS 似乎没问题,但我真的无法从 PDF.js 获得更多信息,真正的原因是 PDF 加载失败。有遇到过相同情况的吗?

原文由 jcbvm 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2k
2 个回答

终于找到问题了。我的服务器没有将 Access-Control-Allow-Credentials: true 标头传递给响应,这是必需的(xhr 请求是使用 xhr.withCredential 发送的)。

CORS 现在可以正常工作了。

在以下位置找到解决方案: https ://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-with-cross-origin-resource-sharing/

原文由 jcbvm 发布,翻译遵循 CC BY-SA 3.0 许可协议

PDF.js 社区没有帮助,多年后仍然没有明确的答案让 viewer.html 与 cors 一起工作。要绕过所有阻止跨浏览器问题的 JS 代码,您可以执行以下步骤:

这个解决方案是使用他们的默认 viewer.html,这已经很好地完成了,带有 css 和所有功能),并且不必自己构建整个查看器。

  1. 确保当您使用 pdf.js 时,您的请求发送标头 - ORIGIN
  2. 确保无论您使用的是什么服务器,您都可以为 CORS 附加标头,

IE:访问控制允许来源*

如您所知,要使用查看器,您应该使用: https://yourserver/dir/viewer.html?file=PDF_URL

pdf 的 URL 应该被 urlencoded 所以当你传递链接时,使用代码:

 var urlEncoded = encodeURI(url);

编辑 viewer.js

  1. 搜索加载 PDF 文件/URL 的函数(第 ~1325 行):“var loadingTask = (0, _pdfjsLib.getDocument)”或“getDocument”

  2. 在该行上方,当您调用 viewer.html?file=url 时,从 get params 获取 pdf 的 url(如果您使用 CDN 服务器,它可能有 get params):

 /*
fetch the filename and params from the [viewer.html?file=some.place/on.the/internet/somefile.pdf?Expiry=2343243&somekey=3342343&other], which is the part [some.place/on.the/internet/somefile.pdf?Expiry=2343243&somekey=3342343&other]
Note: Use regex if you please.... Here is just for simplicity sake
*/
let _realURL =  window.location.href;

// split away the html and get the file=xxxx
let getParamsIndex = _realURL.indexOf("?");
let fileParamKeyValue = _realURL.substring(getParamsIndex+1);

// get the pdf file plus all it's required get params (if exists)
let getEqualsIndex = fileParamKeyValue.indexOf("=");
let pdfFile = fileParamKeyValue.substring(getEqualsIndex+1);

//original line to search
loadingTask = (0, _pdfjsLib.getDocument)(parameters);
  1. 现在你有了 pdf 文件,你改变现有的代码如下:
 //don't use this which breaks if your pdf requires get parameters
//var loadingTask = (0, _pdfjsLib.getDocument)(parameters);
//uses the pdfFile url link we created above
var loadingTask = (0, _pdfjsLib.getDocument)(pdfFile);
  1. 搜索“throw new Error(‘file origin does not match”,关于第 1865 行
  2. 注释掉这个 javascript 检查文件来源
  if (fileOrigin !== viewerOrigin) {
        //don't throw the error, allow the file to be retrieved!!!!
        //throw new Error('file origin does not match viewer\'s');
 }
  1. 注意:在第 1853 行,您会看到 -
 var HOSTED_VIEWER_ORIGINS = ['null', 'http://mozilla.github.io', 'https://mozilla.github.io'];

您可以使用它来指定允许 CORS 的特定服务器,但通过禁用抛出异常,您可以接受任何服务器。无论如何,如果他们想让我们使用它,为什么他们还要把这个 HOSTED_VIEWER_ORIGINS 放在基本代码中呢?

原文由 sboy 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题