我正在嘗試將用戶添加到使用谷歌進行身份驗證的實時資料庫中,如下所示
document.getElementById("btnGoogleLogin").addEventListener('click', function () {
signInWithPopup(auth, provider)
.then((result) => {
// This gives you a Google Access Token. You can use it to access the Google API.
const credential = GoogleAuthProvider.credentialFromResult(result);
const token = credential.accessToken;
// The signed-in user info.
const user = result.user;
const userId = user.uid;
const email = user.email;
const imageUrl = user.photoURL;
const name = user.displayName;
const dbRef = ref(database);
console.log("Current User:" userId);
get(dbRef, '/users' userId).then((snapshot) => {
if (snapshot.exists()) {
console.log(snapshot.val());
} else {
console.log("First time user..Need to add it to db");
writeUserData(userId, email, imageUrl, name)
}
}).catch((error) => {
console.error(error);
});
}).catch((error) => {
// Handle Errors here.
const errorCode = error.code;
const errorMessage = error.message;
// The email of the user's account used.
const email = error.email;
// The AuthCredential type that was used.
const credential = GoogleAuthProvider.credentialFromError(error);
console.log(error);
});
});
function writeUserData(userId, email, imageUrl, name) {
set(ref(database, '/' userId), {
email: email,
imageUrl: imageUrl,
name: name
})
.then(() => {
window.location.href = "https://www.mysite.default.html";
})
.catch((error) => {
// The write failed...
});
}
問題是它第一次在用戶資料庫下添加用戶,并且當使用 google 登錄的新用戶沒有添加到現有用戶資料庫而是添加到身份驗證中時。
我不知道如何擺脫這個。
uj5u.com熱心網友回復:
首先,正如@Frank 所評論的,必須有一個and/之間。然后只采用Query(或DatabaseReference)型別的 1 個引數,但您傳遞的是2,因此正在查詢,這意味著整個資料庫。默認情況下,資料庫可能為空,因此第一個用戶被添加,但之后將始終為真,并且不會添加新用戶。'users'userIdget()get()dbRefsnapshot.exists()
使用child()創建DatabaseReference要解決此問題:
import { child, get } from "firebase/database"
const userRef = child(dbRef, 'users/' userId);
get(userRef).then((snapshot) => {
if (snapshot.exists()) {
console.log(snapshot.val());
} else {
console.log("First time user..Need to add it to db");
writeUserData(userId, email, imageUrl, name)
}
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/400050.html
標籤:javascript 火力基地 火力实时数据库 谷歌登录
