7

양식 입력으로 Facebook API를 사용하여 데이터를 가져 오려고했습니다. 현재 사용자의 위치를 ​​가져 오기 전까지는 모든 것이 잘되었습니다.Uncaught TypeError : 정의되지 않은 'name'속성을 읽을 수 없습니다.

현재 사용자가 자신의 위치 (그가 살고있는 곳)를 공유 한 경우 아무런 문제가 없습니다. 그러나 사용자가 페이스 북에서 자신의 위치를 ​​공유하지 않은 경우 오류가 발생합니다. Uncaught TypeError: Cannot read property 'name' of undefined

다음은 내가 사용 해본 코드입니다. 당신이 그것을 해결하는 방법을 어떤 생각이 있다면, 여기 언급하십시오 :

<div id="fb-root"></div> 
<script> 
    // Additional JS functions here 
    window.fbAsyncInit = function() { 
    FB.init({ 
     appId  : '*******', // App ID 
     status  : true, // check login status 
     cookie  : true, // enable cookies to allow the server to access the session 
     xfbml  : true // parse XFBML 
    }); 

    FB.getLoginStatus(function(response) { 
    if (response.status === 'connected') { 

    FB.api('/me', function(response) { 
    document.getElementById("user_login").value="FB - " + response.username; 
    document.getElementById("user_email").value=response.email; 
    document.getElementById("first_name").value=response.first_name; 
    document.getElementById("last_name").value=response.last_name; 
    document.getElementById("user_url").value=response.link; 
    document.getElementById("fbid").value=response.id; 
    if(response.location !== 'undefined') 
    { 
    document.getElementById("location").value=response.location.name; 
    alert(response.location.name); 
    } 
    document.getElementById("registerform").submit(); 

}); 

    } else if (response.status === 'not_authorized') { 
    alert('error'); 
    } else { 
    alert('Please Log In!'); 
    } 
}); 

    }; 

    // Load the SDK Asynchronously 
    (function(d){ 
    var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0]; 
    if (d.getElementById(id)) {return;} 
    js = d.createElement('script'); js.id = id; js.async = true; 
    js.src = "//connect.facebook.net/en_US/all.js"; 
    ref.parentNode.insertBefore(js, ref); 
    }(document)); 
</script> 

답변

16

을이 라인에 : response.location문자열"undefined"없는 경우

if(response.location !== 'undefined') 

이 ... 당신이 확인하고 있습니다. undefined"undefined" 문자열이 아니기 때문에 조건은 true입니다. 그런 다음 response.location.name을 사용하고 response.locationundefined 인 경우 오류가 발생합니다.

당신은 아마 의미 중 하나

if(response.location) 

또는

if(typeof response.location !== 'undefined') 
+0

감사합니다! 내 실수는 ... –

+0

@IdoDoron : 아무 걱정, 도움이 된 것을 기쁘게 생각합니다! 쉬운 실수. –

관련 문제