我正在尝试使用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>
最佳答案
如果应用未经授权,则响应对象将不包含authResponse
属性-因此,您会看到错误。
你想要的是
uid = response.authResponse
? response.authResponse.userID
: null;
或简单地
uid = response.authResponse && response.authResponse.userID || null;
或简单地
uid = response.authResponse && response.authResponse.userID;