未捕获的ReferenceError:未定义init

时间:2015-08-06 05:27:15

标签: javascript cors

我是一个javascript的新手,想要学习一些东西,我一直在想,我在https://developers.google.com/api-client-library/javascript/features/cors找到了这个我可以使用cors所以我可以访问像kissflow一样的谷歌API,我不知道是否我正确的方式。所以这就是事情,我使用上述网站中描述的独立Auth客户端,但每次我试图运行程序时出现错误提示

Uncaught ReferenceError: init is not defined

我刚刚在

的网站上复制了代码
<script src="https://apis.google.com/js/api.js"
type="text/javascript">
</script>`<script type="text/javascript">`
//<![CDATA[gapi.load('auth', init);//]]>
</script>

1 个答案:

答案 0 :(得分:-1)

试试这个:

<script src="https://apis.google.com/js/api.js"
type="text/javascript">
</script>
<script>
gapi.load("client:auth2", function() {
  gapi.auth2.init({client_id: "<YOUR_CLIENT_ID>"});
});
</script>

确保您在本地托管它,并在创建客户端 ID 时,添加带有端口的 localhost URL。如果没有 URL,客户端 ID 将不会发回正确的响应,从而导致错误。由于客户端ID不支持“file:///”,你必须使用虚拟主机服务什么的,或者更简单的方法,只需下载最新的python并设置一个本地主机服务器即可。

最新的python下载:https://www.python.org/downloads/

设置服务器:https://developer.mozilla.org/en-US/docs/Learn/Common_questions/set_up_a_local_testing_server#running_a_simple_local_http_server

请注意,有时您必须使用“py”而不是“python”,因为我懒得研究?。

要实际启动登录并使用 API:

<script>
function authenticate() {
return gapi.auth2.getAuthInstance().signIn({scope: ""/*Declare scopes with spaces in between, depends on API you're using*/})
  .then(function() { console.log("Sign-in successful"); },
  function(err) { console.error("Error signing in", err); });
}

function loadClient() {
  gapi.client.setApiKey("<YOUR_API_KEY>");
  return gapi.client.load(""/*Declare discovery document, depends on API you're using*/)
  .then(function() { console.log("GAPI client loaded for API"); },
  function(err) { console.error("Error loading GAPI client for API", err); });
}

function execute() {
  return gapi.client.classroom.courses.list({}) //Used classroom courses list as an example, but use the apropriate API Fields, found in your method's "Overview" section on the API Documentation
  .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: "<YOUR_CLIENT_ID>"});
});

authenticate().then(loadClient).then(execute)
</script>

请注意,有时您必须清除缓存才能使其正常工作(我的意思是,对我有用),所以如果您遇到问题,请尝试这样做。