gapi.client.load无法正常工作

sha*_*r90 3 javascript google-api url-shortener google-url-shortener google-api-client

我有以下代码,这应该是使用google api javascript客户端的简单示例,并且只显示硬编码缩短URL的长格式URL:

<script>
  function appendResults(text) {
    var results = document.getElementById('results');
    results.appendChild(document.createElement('P'));
    results.appendChild(document.createTextNode(text));
  }

  function makeRequest() {

    console.log('Inside makeRequest');

    var request = gapi.client.urlshortener.url.get({
      'shortUrl': 'http://goo.gl/fbsS'
    });

    request.execute(function(response) {
      appendResults(response.longUrl);
    });
  }

  function load() {

    gapi.client.setApiKey('API_KEY');
    console.log('After attempting to set API key');
    gapi.client.load('urlshortener', 'v1', makeRequest);
    console.log('After attempting to load urlshortener');
  }
</script>
<script src="https://apis.google.com/js/client.js?onload=load"></script>
Run Code Online (Sandbox Code Playgroud)

除了使用实际的API密钥而不是文本"API_KEY".

控制台输出简单:

尝试设置API密钥后

尝试加载urlshortener后

但我从来没有看到'inside makeRequest',它位于makeRequest函数内部,这是调用gapi.client.load的回调函数,让我相信函数无法正常工作(或者无法完成).

任何人都可以阐明为什么会这样,以及如何解决它?

提前致谢.

sha*_*r90 11

花了几个小时来搜索问题后,我发现问题是因为我在本地计算机上运行此文件而不是在服务器上运行.

当您在chrome上运行上述代码时,您在开发人员控制台中收到此错误"无法将消息发布到文件://.收件人的来源为null".

出于某种原因,javascript仅在实际服务器或类似XAMPP或WAMP上运行时加载.

如果有任何专家可以解释为什么会发生这种情况,那么学习真的很棒.

希望这有助于像我这样的其他小说:D


123*_*345 5

简短回答(http://code.google.com/p/google-api-javascript-client/issues/detail?id=46):

The JS Client does not currently support making requests from a file:// origin.
Run Code Online (Sandbox Code Playgroud)

答案很长(http://en.wikipedia.org/wiki/Same_origin_policy):

The behavior of same-origin checks and related mechanisms is not well-defined
in a number of corner cases, such as for protocols that do not have a clearly 
defined host name or port associated with their URLs (file:, data:, etc.). 

This historically caused a fair number of security problems, such as the 
generally undesirable ability of any locally stored HTML file to access all 
other files on the disk, or communicate with any site on the Internet.
Run Code Online (Sandbox Code Playgroud)