我正在尝试使用Facebook JavaScript SDK实现授权功能。当我运行它时,检查控制台我看到错误。
uncaught TypeError: Cannot read property 'userID' of undefined
代码段
<div id="fb-root"></div>
<!-- Load the Facebook JavaScript SDK -->
<script src="//connect.facebook.net/en_US/all.js"></script>
<script>
var appId = 'APP_ID';
var uid;
// Initialize the JS SDK
FB.init({
appId: '413026618765431',
cookie: true,
});
// Get the user's UID
FB.getLoginStatus(function(response) {
uid = response.authResponse.userID ? response.authResponse.userID : null;
});
function authUser() {
FB.login(function(response) {
uid = response.authResponse.userID ? response.authResponse.userID : null;
}, {scope:'email,publish_actions'});
}
</script>
答案 0 :(得分:4)
如果应用未获得授权,则响应对象将不包含authResponse
属性 - 因此您看到错误。
你想要的是
uid = response.authResponse
? response.authResponse.userID
: null;
或只是
uid = response.authResponse && response.authResponse.userID || null;
或只是
uid = response.authResponse && response.authResponse.userID;
答案 1 :(得分:2)
这是适用于我的代码行(iOS和Android):
var uid = response.authResponse.userID || response.authResponse.userId;
userID未定义,但iOS未定义userId。
答案 2 :(得分:1)
您是否尝试过response.authResponse.userId?