0

I am trying to download a file from an url (chrome drive file) in javascript; and want to send it to my backend (php - laravel).

var url = file.downloadUrl !== undefined ? file.webContentLink : file.exportLinks['application/pdf'];

console.log(url) // if I go to url, it downloads the file

if (url !== undefined) {
      var remote = new XMLHttpRequest();
      remote.open('GET', url);
      remote.setRequestHeader('Authorization', 'Bearer ' + gapi.client.getToken().access_token);
      remote.setRequestHeader('Access-Control-Allow-Origin', '*');
      remote.onload = function(e) {
          vm.handle_download(remote.responseText, file, 200); // do something with the fetched content;
      };
      remote.onerror = function(e) {
             vm.handle_download('error response', null, remote.statusText);
      };
      remote.send();
} else vm.handle_download('no downloadable url', {
     file: null,
     status: 'error'
});

and on handle

handle_download: function (content, file, status) {
        if (status !== 200) {
            console.log('error occured on status')
            return;
        }
}

Failed to load https://drive.google.com/uc?id=1D12321ofd4CNG-m9_Mp4aiDcnibNf&export=download: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://test.dev' is therefore not allowed access.

senty
  • 12,385
  • 28
  • 130
  • 260

1 Answers1

1

This is an intended behavior due to same origin policy in the web. Since you're doing this for testing purposes, try this Allow-Control-Allow-Origin chrome extension.

You can read more about how to implement this in Using CORS tutorial. This SO post may also offer additional insight.

ReyAnthonyRenacia
  • 17,219
  • 5
  • 37
  • 56