即使身份验证成功,也无法写入 firebase 实时数据库

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();
})