首页 > 解决方案 > Google 登录:无法访问 GoogleAuth 对象

问题描述

我正在尝试将 Google 登录添加到我的网络应用程序。gapi.auth2.init() 成功,当我将 GoogleAuth 定义为 gapi.auth2.getAuthInstance() 时,它不会引发错误。但是,当我尝试运行 GoogleAuth.signIn() 时,它抱怨它不是一个函数。我究竟做错了什么?

这一切都在一个功能性的 React 组件中:

let GoogleAuth

const googleSignIn = () => {
    GoogleAuth.signIn()
    .then(() => {
        console.log('signed in')
    })
    .catch(err => {
        console.log('failed to sign in: ')
        console.log(err)
    })
}

window.gapi.load('auth2', () => {
    gapi.auth2.init({
        client_id: googleClientId
    })
    .then(() => {
        console.log('google auth initialized') // This shows in the console
        GoogleAuth = gapi.auth2.getAuthInstance() // This does not throw an error
    }, err => {
        console.log('google auth failed to initialize')
        console.log(err)
    })
})

return <GoogleLoginButton text="Log in with Google" onClick={googleSignIn} />

我等到看到“google auth initialized”消息,然后单击按钮,但它会引发如上所述的错误。

标签: javascriptgoogle-oauth

解决方案


事实证明 gapi.auth2.getAuthInstance() 返回一个承诺,而不是一个对象(与文档相反,感谢 Google),所以我只需要这样做:

gapi.auth2.getAuthInstance()
.then(instance => {
    GoogleAuth = instance
}, err => {
    console.log(err)
})

现在它起作用了!


推荐阅读