Pinterest 检索图片时出现 CORS 错误

Pinterest CORS error when retrieving picture

为了一个项目,我从多个社交网络中检索图片。我使用 Pinterest,我可以列出图钉并用 URL 显示它们。但是当我想用 XMLHttpRequest 下载图片时,我收到一个 CORS 错误。

是因为 Pinterest 的政策还是有其他方法?

这是我的代码

console.log("Url de l'image: " + this.snURL);
            //bug avec Pinterest
            var xhr = new XMLHttpRequest();
            var _self = this;
            xhr.onload = function () {
                var reader = new FileReader();
                reader.onloadend = function () {
                    console.log(reader.result);
                    _self.initRealisationLocalStorage();
                    workInProgress.Start('Traitement de l\'image');
                    workInProgress.Info('Traitement de l\'image');
                    $scope.uploadPhotoNotLocalstorage(reader.result);
                }
                reader.readAsDataURL(xhr.response);
            };
            xhr.open('GET', this.snURL);
            //xhr.setRequestHeader("Access-Control-Allow-Origin","*");
            xhr.responseType = 'blob';
            xhr.send();
});

如果有人有解决方案或运行解释,我会很高兴听到它

当直接从浏览器 (javascript) 调用另一个域时,存在防止任意包含外部数据的安全措施。

如果允许,通常是定义 CORS header "Access-Control-Allow-Origin" 的服务器,但我想这对于 Pinterest 添加调用其 API 的每个域来说是不可接受的。

为此,他们建议使用他们的 SDK here and it will use the redirect url you configure in your Pinterest App. as a fallback, otherwise they will use the postMessage API

出于这个原因(浏览器端的 CORS 限制),我认为您不能直接从您的 JavaScript 直接对他们的 API 进行 AJAX 调用,请参阅 this post.

另一种可能性是在你这边创建一个代理后端(比如 node.js 项目),它向 Pinterest API 查询,然后你从你的Javascript AJAX 您不会遇到 CORS 问题,因为调用的后端会在您身边,即使它部署在不同的域中,您也可以自己在该后端设置 CORS headers。

我认为 SDK 方式可以解决您的问题,并且它看起来是从浏览器直接调用 API 时唯一的方式。