javascript 跨域资源共享策略拒绝跨域图像加载

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17990678/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 10:21:50  来源:igfitidea点击:

Cross-origin image load denied by Cross-Origin Resource Sharing policy

javascriptgoogle-mapshtml2canvas

提问by HoangHieu

I use html2canvas (from html2canvas.hertzen.com) to capture screenshot. I got this strange error like this: The code of my webpage is put on one host, say Host A. If my webpage contains an image on another host, say Host B, then I hit this error: Cross-origin image load denied by Cross-Origin Resource Sharing policy

我使用 html2canvas(来自 html2canvas.hertzen.com)来捕获屏幕截图。我遇到了这样一个奇怪的错误:我的网页代码放在一个主机上,比如主机 A。如果我的网页包含另一台主机上的图像,比如主机 B,那么我遇到了这个错误:跨域图像加载被拒绝跨域资源共享策略

However, the confusing part is that if Host B is facebook (my image is a direct link to facebook https://fbcdn-profile-a.akamaihd.net/hprofile-ak-ash4/372701_100000684388457_1551561655_q.jpg) then the error disappear.

然而,令人困惑的部分是,如果主机 B 是 facebook(我的图片是到 facebook 的直接链接 https://fbcdn-profile-a.akamaihd.net/hprofile-ak-ash4/372701_100000684388457_1551561655_q.jpg)那么错误就会消失。

My function

我的功能

html2canvas([document.body], {
                    useCORS : true,
                    logging : true,
                    onrendered : function(canvas) {
                        document.body.appendChild(canvas);
                        var myImage = canvas.toDataURL("image/png");
                        window.open(myImage);
                    }

Anyone got a tip? Tks

有人有提示吗?塔克斯

solution

解决方案

 html2canvas([document.body], {
                                    useCORS: true,
                                    proxy: "Server",
                                    onrendered : function(canvas) {                               
                                        ListUCapture = canvas.toDataURL("image/png");                                                           
                                    }
                     });
Server is server of node.js

回答by Niklas

If you wish to load cross-origin images to a canvas, you need to either serve the image with cross-origin headers or under the same origin. That image under Facebook is served with the following header option set:

如果您希望将跨域图像加载到画布,您需要使用跨域标题或在同一源下提供图像。Facebook 下的该图像使用以下标题选项集提供:

Access-Control-Allow-Origin:*

Access-Control-Allow-Origin:*

Meaning, it can be cross-origin loaded with the useCORSoption. However, it would appear that your Host B isn't serving them with cross-origin headers set.

意思是,它可以跨域加载useCORS选项。但是,您的主机 B 似乎没有为它们提供跨域标头集。