javascript - Google API 演示在本地无法运行;GAPI 为空
问题描述
我从本教程中复制了 Google 的演示代码: https ://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/get
但是,当我尝试在本地运行它时,出现以下错误。
testoJS.html:14 Uncaught TypeError: Cannot read property 'signIn' of null
at authenticate
gapi
即使代码预先导入了 api 模块,我也不确定为什么变量为空。
这是我的代码的副本;我的客户端 ID、API 密钥和电子表格 ID 是正确的 - 我在上述网站的“试用此 API”部分中测试了这些值。http 请求在那里工作得很好,并返回电子表格的内容。但是,我似乎无法在本地运行它。
<html>
<head></head>
<body>
<script src="https://apis.google.com/js/api.js"></script>
<script>
/**
* Sample JavaScript code for sheets.spreadsheets.values.get
* See instructions for running APIs Explorer code samples locally:
* https://developers.google.com/explorer-help/guides/code_samples#javascript
*/
function authenticate() {
return gapi.auth2.getAuthInstance()
.signIn({scope: "https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/drive.readonly https://www.googleapis.com/auth/spreadsheets https://www.googleapis.com/auth/spreadsheets.readonly"})
.then(function() { console.log("Sign-in successful"); },
function(err) { console.error("Error signing in", err); });
}
function loadClient() {
gapi.client.setApiKey("API_KEY");
return gapi.client.load("https://content.googleapis.com/discovery/v1/apis/sheets/v4/rest")
.then(function() { console.log("GAPI client loaded for API"); },
function(err) { console.error("Error loading GAPI client for API", err); });
}
// Make sure the client is loaded and sign-in is complete before calling this method.
function execute() {
return gapi.client.sheets.spreadsheets.values.get({
"spreadsheetId": "SPREADSHEETID",
"range": "A1:D4"
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) { console.error("Execute error", err); });
}
gapi.load("client:auth2", function() {
gapi.auth2.init({client_id: "CLIENT_ID"});
});
</script>
<button onclick="authenticate().then(loadClient)">authorize and load</button>
<button onclick="execute()">execute</button>
</body>
</html>
解决方案
推荐阅读
- php - laravel spark中如何创建本地发票?
- python - 用空格表示的树形结构
- assembly - 尝试从软盘驱动器读取扇区时,INT 13、2 在 x86 实模式下挂起
- python - python中具有多个值的同名键
- javascript - Fancybox3 左右跳过按钮
- javascript - 获取多个元素的第 N 个父级
- firebase - 在 Flutter 中,将 firebase 实时数据保存在本地存储 json 中,并从 json 填充列表视图
- java - IllegalStateException : Gremlin 服务器必须配置为使用 JanusGraphManager
- php - 浏览器在进程完成后清除输出,但我想保留它
- docker - 我无法在 Linux mint 中启动我的 docker