我想从本地主机(WAMP 环境)对 Google FusionTables API 进行 JSON-RPC 调用(以及一些其他 API)使用 Google Client Library for JavaScript
我采取的步骤:
- 在 Google Developer Console 上设置一个项目
- 启用了 FusionTables API
- 创建了一个服务帐户并下载了 JSON 文件。
- 成功加载带有 auth 包的 JS 客户端库:
gapi.load('client:auth2', initAuth);
- 通过以下 3 种方式构造了 init 方法参数:
- 逐字下载的 JSON
- 修改下载的 JSON 以包含范围
- 仅客户端 ID 和范围
- 尝试(但失败)初始化 GoogleAuth 实例:
gapi.auth2.init(params)
function failed(reason) { console.log(reason); } gapi.load('client:auth2', initAuth); function initAuth() { var APIkey = 'MY API KEY'; gapi.client.setApiKey(APIkey); //I understand this to be unnecessary with authorized requests, included just for good measure var GDTSAKey = 'MY SERVICE ACCOUNT KEY'; var scopes = 'https://www.googleapis.com/auth/fusiontables'; gapi.auth2.init({ client_id: "101397488004556049686", scope: 'https://www.googleapis.com/auth/fusiontables' }).then(signin, failed("couldn't initiate")); //passing the downlaoded JSON object verbatim as parameter to init didn't work either } //initAuth() function signin() { gapi.auth2.getAuthInstance().signIn().then(makeAPIcall), failed("couldn't sign-in"); } function makeAPIcall(){ gapi.client.load('fusiontables', 'v2', function(){ var tableId = '1PSI_...'; var table = gapi.client.fusiontables.table.get(tableId); document.querySelector("#result").innerHTML = table; }); }
基于 JS client library >> Samples
gapi.auth2.init
方法调用第二个回调(据我所知是一个错误处理程序):失败(“无法启动”),但奇怪的是,我也得到了“无法登录”只能源自提供的成功处理程序。这是怎么回事?我如何让它发挥作用?
注意:如果无法使用 JS 客户端库,我只愿意尝试 CORS/xhr。
最佳答案
What's going on?
您正在尝试将服务帐户与不支持服务帐户的 Google JavaScript 客户端库一起使用。
How do I get this to work?
切换到 Oauth2 身份验证,或者如果您必须使用服务帐户,则切换到服务器端语言,例如 PHP 或 python。其中支持服务帐号认证。
关于javascript - 验证服务帐户以使用 JavaScript 客户端库调用 Google API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39825592/