2

For a project, I retrieve pictures from multiples Social Network. I use Pinterest, and I can list the pins and display them with the URL. But when I want to download a picture with an XMLHttpRequest, I receive a CORS error.

Is it because of the policy of Pinterest or is there an other way to do I?

Here is my code

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();
});

If someone have a solution or ran explaination I'll be happy to hear it

1 Answers1

0

When calling another domain from a browser directly (javascript) there is a security to prevent arbitrary inclusion of external data.

When this is allowed, it is normally the server who define the CORS header "Access-Control-Allow-Origin" but I guess this is not acceptable for Pinterest to add every domains calling their API.

For that they recommend to use their 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

I don't think you can just make AJAX calls straight to their API from your JavaScript for this reason (CORS restriction on the browser side), see this post.

Another possibility is to create a proxy backend on your side (like a node.js project) which make the query to the Pinterest API and then you query that proxy on your side from your Javascript AJAX You will not have CORS issue as the backend called would be on your side, and even it is deployed in a different domain you can set the CORS headers on that backend yourself.

I think the SDK way would address you issue and it looks to be the only way to do it when calling the API from a browser directly.

рüффп
  • 5,172
  • 34
  • 67
  • 113
  • 1
    Thank you for your response, I've never heard about postMessage, it can be usefull. I abort Pinterest purpose because it wasn't relevent for my project but I faced the same issue with Google Photo picture, when I tried to download the picture form url. To resolve it I use my backend with this php function: [file_get_contents](http://php.net/manual/en/function.file-get-contents.php). – digitalTrilunaire Jul 24 '17 at 07:57