3

다음 코드는 google api javascript 클라이언트를 사용하는 간단한 예라고 가정하고 하드 코딩 된 단축 URL의 긴 형식 URL 만 표시합니다.gapi.client.load not working

<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> 

'API_KEY'대신 실제 API 키가있는 경우를 제외하고

콘솔 출력은 단순히 :

을 urlshortener로드하려고 시도 후

핵심 API를 설정하려고하지만 난하여 makeRequest 기능, 내부에 '내부하여 makeRequest'를 보지 못할 후에하는 는 gapi.client.load 호출에 대한 콜백 함수로, 함수가 작동하지 않거나 완료되지 못했다고 생각하게합니다.

누군가가 왜 그렇게 될지, 어떻게 고칠 수 있습니까?

미리 감사드립니다.

답변

11

문제를 검색하는 데 많은 시간을 할애하여이 파일을 서버가 아닌 로컬 시스템에서 실행했기 때문에 문제가 있음을 발견했습니다.

크롬에서 위 코드를 실행하면 개발자 콘솔에서이 오류가 발생합니다. "file : //.받는 사람의 기점이 null입니다."

실제 서버 나 XAMPP 또는 WAMP에서 실행될 때만 javascript가로드됩니다.

이런 일이 발생하는 이유를 밝힐 수있는 전문가가 있으면 배우기에 정말 충분할 것입니다.

희망이 거기에 나 같은 다른 사람의 noobies을하는 데 도움이 : D

+1

난 그냥 추가 할 하나 더. 인터넷의 일부 호스팅 또는 웹 서버에 업로드하는 것은 필수 사항은 아닙니다. localhost에서 로컬 Apache 또는 유사 (예 : AppServ)에서 작동하도록 할 수 있습니다. – InsaurraldeAP

+0

WRONG : "문제가있는 시간을 보내고 나서, 로컬 시스템에서이 파일을 실행했기 때문에 문제가 있음을 알았습니다."- 웹 서버를 실행하는 동안 로컬 시스템에서 실행할 수 있습니다. 당신의 고객. 예를 들어, 파이썬 간단한 HTTP 서버를보십시오 : http://www.linuxjournal.com/content/tech-tip-really-simple-http-server-python 이것은 창문에서도 작동합니다. –

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. 

긴 대답 (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.