CORS authorization on google sheets API requests

2020-06-04 16:03发布

I'm trying to read data from a google spreadsheet by retrieving a cell based feed via the sheets API. The spreadsheet is private, so I'm using oauth 2.0 to authorize my requests.

Retrieving basic infos about my drive account via https://spreadsheets.google.com/feeds/spreadsheets works fine, but when I try to access the data from on of my spreadsheets directly via XMLHttp GET Request to https://spreadsheets.google.com/feeds/cells

I'm getting an "No 'Access-Control-Allow-Origin' header is present on the requested resource" error.

I've set the correct Authorization Token via

 xhr.setRequestHeader('Authorization', 'Bearer ' + token);

and tried to "activate" CORS via

 xhr.setRequestHeader('Access-Control-Allow-Credentials', 'true');

To no avail.

Any tipps on how to access this resource ?

Thanks !

3条回答
▲ chillily
2楼-- · 2020-06-04 16:23

Fixed this very same issue just today. And I did not need to enable/activate CORS as I've read that some firewalls will strip out the headers for security. http://promincproductions.com/blog/server-proxy-for-cross-site-scripting-cors/

In a global part of your js code, add in a function ...

window.googleDocCallback = function () { return true; };

Then, to the URL in your AJAX (GET assumed?) request, if you have no URI params, append ?callback=googleDocCallback

and if you do have other params, append &callback=googleDocCallback

For more info, please see: https://jvaneyck.wordpress.com/2014/01/07/cross-domain-requests-in-javascript/

查看更多
戒情不戒烟
3楼-- · 2020-06-04 16:30

You need to send a GET request. Make sure that there are no headers sent (not even content-type headers).

查看更多
Lonely孤独者°
4楼-- · 2020-06-04 16:43

Google Sheets API has a known bug that doesn't support CORS for POST requests. Can you confirm that you are in fact making a GET request and not a POST/PUT/DELETE?

查看更多
登录 后发表回答