我正试图实现signInWithRedirect()函数,但是-奇怪的是,它不起作用。在下面的代码中,Check 2
和Check 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));
}
};
此外,如果我使用完全相同的谷歌帐户登录与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()
}, [])
注意事项:
- 在某些情况下,getRedirectResult()不会抛出错误,说一个帐户已经存在与另一个登录方法:https://github.com/firebase/firebase-js-sdk/issues/6051。
- 这些错误问题可以通过电子邮件验证流程解决,如下所示:https://firebase.google.com/docs/auth/users#verified_email_addresses