我有一个关于PDF.js和CORS配置的问题。
我从域A将PDF.js加载到iframe中,参数为文件(服务器的完整路径,它将返回一个pdf文档)。PDF.js将使用origin: domain A向域B中的服务器创建请求。域B上的服务器返回标题为Access-Control-Allow-Origin: domain A的pdf文档,到目前为止一切正常。
在我的网络选项卡中,我看到对服务器的请求,它返回一个200 status OK,但PDF.js抛出了一个错误Unexpected server response (0) while retrieving PDF <url>。
问题是,这里发生了什么,CORS看起来还好,但我真的无法从PDF.js获得更多信息,真正的原因是PDF无法加载。有没有人遇到过同样的情况?
发布于 2016-09-08 00:56:40
终于找到了问题所在。我的服务器没有将Access-Control-Allow-Credentials: true头传递给所需的响应(使用xhr.withCredential发送了xhr请求)。
CORS现在工作正常。
在以下网址找到解决方案:https://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-with-cross-origin-resource-sharing/
发布于 2018-05-23 16:58:19
PDF.js社区没有帮助,几年后仍然没有明确的答案来让viewer.html与cors一起工作。要绕过所有阻止跨浏览器问题的JS代码,您可以执行以下步骤:
这个解决方案是使用他们的默认viewer.html,这已经做得很好了,与css和所有功能),而不是必须构建您的整个查看器本身。
的报头
即Access-Control-Allow-Origin *
如您所知,要使用查看器,您应该使用:https://yourserver/dir/viewer.html?file=PDF_URL
应该对pdf的URL进行urlencoded,以便在传递链接时使用以下代码:
var urlEncoded = encodeURI(url);
编辑viewer.js
/*
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);
//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);
if (fileOrigin !== viewerOrigin) {
//don't throw the error, allow the file to be retrieved!!!!
//throw new Error('file origin does not match viewer\'s');
}
var HOSTED_VIEWER_ORIGINS = ['null', 'http://mozilla.github.io', 'https://mozilla.github.io'];
您可以使用它来指定允许CORS的特定服务器,但是通过禁用throws异常,您可以接受任何服务器。无论如何,如果他们想让我们使用这个HOSTED_VIEWER_ORIGINS,为什么还要把它放在基本代码中呢?
发布于 2019-04-19 23:09:24
当我在pdfjslib.getDocument中提供我的PDF.js文件的路径时,CORS问题也来到了我的PDF。我通过在getDocument方法中提供pdf文件的数据URI解决了这个问题。我将pdf文件的数据URI设置为:
dataURI = "data:text/plain;base64," + (Get base64 of PDF from online tool or you can generate it by javascript as well);https://stackoverflow.com/questions/39373329
复制相似问题