Uncaught TypeError: Cannot read property 'name' of undefined

。_饼干妹妹 提交于 2020-01-02 01:05:22

问题


I tried to fetch data using facebook api into form inputs. Now, everything went just fine until I tried to also fetch the location of the current user.

If the current user have shared his location (Where he is living), then I get no problems. However, if the user hasn't shared his location on facebook, I am getting an error: Uncaught TypeError: Cannot read property 'name' of undefined

Here is the code I've been using. If you have any idea how to solve it, please comment here :)

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

回答1:


On this line:

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

...you're checking if response.location is not the string "undefined". Since undefined is not the string "undefined", the condition is true. Then you try to use response.location.name and as response.location is undefined, you get the error.

You probably meant either:

if(response.location)

or

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


来源:https://stackoverflow.com/questions/15312479/uncaught-typeerror-cannot-read-property-name-of-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!