javascript - Firebase getRedirectResult() 没有解决

标签 javascript firebase firebase-authentication

我正在尝试实现 signInWithRedirect() 函数,但奇怪的是,它不起作用。在下面的代码中,Check 2Check 3 永远不会被记录 - 也不会抛出任何错误:

const signInWithGoogle = async () => {
        try {
            console.log("Check 1")
            await signInWithRedirect(auth, googleAuthprovider);

            console.log("Check 2")
            const result = await getRedirectResult(auth);

            console.log("Check 3");
            if (result) {
                console.log(result.user);
            }

        } catch (e) {
            console.log(e.message.slice(10));
        }
    };

此外,如果我使用完全相同的 Google 帐户通过 signInWithPopup() 方法登录,一切都会按预期进行:

const signInWithGoogle = async () => {
        const result = await signInWithPopup(auth, googleAuthprovider)

            const user = result.user;
            console.log(user)
    };

我非常感谢您的帮助。谢谢!

最佳答案

signInWithRedirect 实际上会离开页面并重定向回您的应用程序,因此您需要在一个单独的函数中处理响应,该函数会在您的应用程序首次加载时触发。

import {
  signInWithRedirect,
  getRedirectResult,
  GoogleAuthProvider,
} from "firebase/auth"
const googleAuthProvider = new GoogleAuthProvider()

// On Button Click
const signUpGoogle = async () => {
  try {
    await signInWithRedirect(auth, googleAuthProvider)
  } catch (error: any) {
    console.log(error)
  }
}
  
  
// When the page loads
const debugRedirectResult = async () => {
  try {
    const result = await getRedirectResult(auth)
    if (result) {
      const details = getAdditionalUserInfo(result)
      console.log(details) // details.isNewUser to determine if a new or returning user
    } else {
      // Everything is fine
    }
  } catch (error) {
    console.log(error) // Debug errors from redirect response
  }
}

例如,在 React 中你会做这样的事情:

// Something like an Auth context provider or App.js
React.useEffect(() => {
  const debugRedirectResult = async () => {
    try {
      const result = await getRedirectResult(auth)
      if (result) {
        const details = getAdditionalUserInfo(result)
        console.log(details) // details.isNewUser to determine if a new or returning user
      } else {
        // Everything is fine
      }
    } catch (error) {
      console.log(error) // Debug errors from redirect response
    }
  }
  signInWithRedirect()
}, [])

注意事项:

关于javascript - Firebase getRedirectResult() 没有解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73004241/

相关文章:

javascript - 如何使用 Turn.js 阻止 .json 请求?

javascript - 在函数中 react 未定义的 this

java - 错误 :null value in entry: streamOutputFolder=null

android - Flutter 和 android studio 错误 : Google Play Store is missing

javascript - firebase登录成功后回调?

javascript - 对范围界定和这个感到困惑

javascript - 在 Controller AngularJs 与服务之间共享数据

javascript - 如何将 firestore 模拟器与 Nextjs 一起使用

javascript - 如何在 html 标记中创建循环以显示数据库中的所有 JSON 子字段?

Firebase,使用REST服务自动登录