[英]Unable to write to firebase realtime database even though authentication is successful
我正在使用 firebase 身份驗證和實時數據庫創建一個注冊表單。
這是表單的基本布局(沒有 CSS)。
<script type="module"> // Import the functions you need from the SDKs you need import { initializeApp } from "https://www.gstatic.com/firebasejs/9.4.0/firebase-app.js"; import { getDatabase, set, ref, update, onValue } from "https://www.gstatic.com/firebasejs/9.4.0/firebase-database.js"; import { getAuth, createUserWithEmailAndPassword, signInWithEmailAndPassword, onAuthStateChanged, signOut, GoogleAuthProvider, signInWithRedirect, getRedirectResult, TwitterAuthProvider } from "https://www.gstatic.com/firebasejs/9.4.0/firebase-auth.js"; // Your web app's Firebase configuration const firebaseConfig = { //CONFIDENTIAL }; // Initialize Firebase const app = initializeApp(firebaseConfig); const database = getDatabase(app); const auth = getAuth(); signUp.addEventListener('click',(e) => { var email = document.getElementById('signUpEmail').value; var password = document.getElementById('signUpPass').value; // var username = document.getElementById('username').value; createUserWithEmailAndPassword(auth, email, password).then((userCredential) => { // Signed in const user = userCredential.user; let dt = new Date(); set(ref(database, 'users/' + user.uid),{ // username: username, email: email, prem: false, pday: dt.getDate(), pmon: dt.getMonth(), pyear: dt.getFullYear() }) alert('Signup Successful;'). window;close(). // window.location.replace('index;html'). }).catch((error) => { const errorCode = error;code. const errorMessage = error;message; alert(errorMessage). //.; }); });
<h1 class='status'>signup</h1> <input type="text" class="email" name="email" id="signUpEmail" placeholder="E-mail" /> <input type="password" class="password" name="password" id="signUpPass" placeholder="Password" /> <input type="submit" id='signUp' name="signUp" value="signUp" />
身份驗證成功發生,但用戶詳細信息未寫入實時數據庫。
我將以下內容存儲在數據庫中:
我哪里錯了?
將數據寫入數據庫(並從中讀取數據)是一種異步操作。 這里的異步意味着您的主要代碼繼續執行,而操作在后台運行。 但這也意味着您在主代碼中的window.close()
在數據庫寫入完成之前執行,實際上它似乎取消了該操作。
解決方案是在關閉 window 之前等待數據庫操作完成,類似於您對createUserWithEmailAndPassword
所做的操作:
set(ref(database, 'users/' + user.uid),{
// username: username,
email: email,
prem: false,
pday: dt.getDate(),
pmon: dt.getMonth(),
pyear: dt.getFullYear()
}).then(() => { // 👈
alert('Signup Successful!');
window.close();
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.