Firebase创建新用户功能失效求助:代码无法生成用户
Firebase注册功能排查与修复
问题描述
使用Visual Studio Code结合Firebase开发用户注册功能,已在Firebase控制台启用邮箱/密码认证,可手动向数据库添加用户,但运行模拟器测试时无法创建新用户,相关代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF=8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Sign Up</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script> <style> body{ display: flex; justify-content: center; align-items: center; height: 100vh; width: 100vw; margin: 0px; } </style> <div class "mb-5"> <h3 class = "mb-3">Sign Up</h3> <input type="text" placeholder="Fullname" id="nameInp" class="form-control mb-3"> <input type="text" placeholder="Email" id="emailInp" class="form-control mb-3"> <input type="text" placeholder="Username" id="userInp" class="form-control mb-3"> <input type="password" placeholder="Password" id="passInp" class="form-control mb-3"> <button type="text" id="sub_btn" class="btn w-100 btn-outline-primary mb-3">Sign Up</button> <a href="login.html" class="badge badge-secondary py-1 w-100">Already Have An Account?</a> </div> <script type="module"> // Import the functions you need from the SDKs you need import { initializeApp } from "https://www.gstatic.com/firebasejs/9.23.0/firebase-app.js"; // TODO: Add SDKs for Firebase products that you want to use // https://firebase.google.com/docs/web/setup#available-libraries // Your web app's Firebase configuration const firebaseConfig = { apiKey: "AIzaSyDj0QJk8Ptz0N_WjHg76iFhY3f2fBmStcM", authDomain: "app-to-test-multiple-users.firebaseapp.com", databaseURL: "https://app-to-test-multiple-users-default-rtdb.firebaseio.com", projectId: "app-to-test-multiple-users", storageBucket: "app-to-test-multiple-users.appspot.com", messagingSenderId: "342422003892", appId: "1:342422003892:web:7d0070e376d055c29737e1" }; // Initialize Firebase const app = initializeApp(firebaseConfig); import { getDatabase, ref, set, child, get } from "https://www.gstatic.com/firebasejs/9.23.0/firebase-database.js"; const db = getDatabase(); // references const name = document.getElementById('nameInp'); const email = document.getElementById('emailInp'); const username = document.getElementById('userInp'); const pass = document.getElementById('passInp'); const submit = document.getElementById('sub_btn'); // validation function isEmptyOrSpaces(str){ return str == null || str.match (/^ *$/) !== null; } function validation(){ let nameregex = /^[a-zA-Z]+$/; let emailregex = /^[a-zA-Z0-9]+@(gmail|yahoo|outlook|)\.com$/; let userregex = /^[a-zA-Z0-9]{5,}$/; if(isEmptyOrSpaces(name.value)|| isEmptyOrSpaces(email.value)|| isEmptyOrSpaces(username.value)|| isEmptyOrSpaces(pass.value)){ alert("you cannot leave any field empty"); return false; } if (!nameregex.text(name.value)){ alert("Name should only contain alphabet letters!"); return false; } if(!emailregex.test(email.value)){ alert("enter a valid email!"); return false; } if(userregex.test(username.value)){ alert("-username must be at least 5 characters long\n-username must not contain spaces"); return false; } return true; } // registers to firebase function RegisterUser(){ if (!validation()){ return; }; const dbRef = ref(db); get(child(dbRef,"UsersList/"+username.value)).then((snapshot)=>{ if(snapshot.exists()){ alert("Account already Exists"); } else { set(ref(db, "UsersList"+ username.value), { fullname: name.value, email:email.value, username: username.value, password: encPass() }) .then(()=>{ alert("user added successfully"); }) .catch((error)=>{ alert("error"+ error); }) } }); } // encryption function encPass(){ var pass12 =CryptoJS.AES.encrypt(pass.value,pass.value); return pass12.toString(); } // events submit.addEventListener('click', RegisterUser); </script> </body>
问题排查与修复
1. HTML结构与标签错误
- class属性语法错误:
<div class "mb-5">缺少等号,应改为<div class="mb-5"> - 按钮类型错误:
<button type="text">应为<button type="button">,否则会默认触发表单提交导致页面刷新 - DOM结构不完整:
<head>标签未闭合,注册表单的div应放在<body>标签内部,修正后的基础结构:
<!DOCTYPE html> <html lang="en"> <head> <!-- 原head内容 --> </head> <body> <!-- 注册表单div --> <div class="mb-5"> <!-- 表单内容 --> </div> <!-- script标签 --> </body> </html>
- 字符编码错误:
<meta charset="UTF=8">应为<meta charset="UTF-8">(等号为笔误)
2. 表单验证逻辑错误
- 正则方法调用错误:
nameregex.text(name.value)应为nameregex.test(name.value)(text是笔误) - 用户名验证逻辑反转:当前代码中
if(userregex.test(username.value))会在用户名符合规则时报错,应改为if(!userregex.test(username.value)),即不符合规则时提示错误:
if(!userregex.test(username.value)){ alert("-username must be at least 5 characters long\n-username must not contain spaces"); return false; }
3. Firebase数据库路径错误
写入数据库时的路径缺少斜杠,"UsersList"+ username.value 会生成类似UsersListjohndoe的节点,正确路径应为"UsersList/"+ username.value,确保用户数据存放在UsersList节点下:
set(ref(db, "UsersList/" + username.value), { fullname: name.value, email: email.value, username: username.value, password: encPass() })
4. 未使用Firebase Auth创建用户
你已在控制台启用邮箱/密码认证,但当前代码仅将用户数据写入实时数据库,未调用Firebase Auth的用户创建接口。需添加Auth相关导入与逻辑:
// 导入Auth模块 import { getAuth, createUserWithEmailAndPassword } from "https://www.gstatic.com/firebasejs/9.23.0/firebase-auth.js"; const auth = getAuth(app); // 修改RegisterUser函数,先创建Auth用户再写入数据库 function RegisterUser(){ if (!validation()){ return; }; const dbRef = ref(db); get(child(dbRef,"UsersList/"+username.value)).then((snapshot)=>{ if(snapshot.exists()){ alert("Account already Exists"); } else { // 先创建Auth用户 createUserWithEmailAndPassword(auth, email.value, pass.value) .then((userCredential) => { const user = userCredential.user; // 再写入数据库 return set(ref(db, "UsersList/" + username.value), { fullname: name.value, email: email.value, username: username.value, uid: user.uid // 关联Auth用户ID }); }) .then(()=>{ alert("user added successfully"); }) .catch((error)=>{ alert("error: " + error.message); }); } }); }
注:Firebase Auth会自动加密存储密码,无需自行加密后存入数据库,建议移除自定义的密码加密逻辑。
修复后完整代码示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Sign Up</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <style> body{ display: flex; justify-content: center; align-items: center; height: 100vh; width: 100vw; margin: 0px; } </style> </head> <body> <div class="mb-5"> <h3 class="mb-3">Sign Up</h3> <input type="text" placeholder="Fullname" id="nameInp" class="form-control mb-3"> <input type="email" placeholder="Email" id="emailInp" class="form-control mb-3"> <input type="text" placeholder="Username" id="userInp" class="form-control mb-3"> <input type="password" placeholder="Password" id="passInp" class="form-control mb-3"> <button type="button" id="sub_btn" class="btn w-100 btn-outline-primary mb-3">Sign Up</button> <a href="login.html" class="badge badge-secondary py-1 w-100">Already Have An Account?</a> </div> <script type="module"> import { initializeApp } from "https://www.gstatic.com/firebasejs/9.23.0/firebase-app.js"; import { getDatabase, ref, set, child, get } from "https://www.gstatic.com/firebasejs/9.23.0/firebase-database.js"; import { getAuth, createUserWithEmailAndPassword } from "https://www.gstatic.com/firebasejs/9.23.0/firebase-auth.js"; const firebaseConfig = { apiKey: "AIzaSyDj0QJk8Ptz0N_WjHg76iFhY3f2fBmStcM", authDomain: "app-to-test-multiple-users.firebaseapp.com", databaseURL: "https://app-to-test-multiple-users-default-rtdb.firebaseio.com", projectId: "app-to-test-multiple-users", storageBucket: "app-to-test-multiple-users.appspot.com", messagingSenderId: "342422003892", appId: "1:342422003892:web:7d0070e376d055c29737e1" }; const app = initializeApp(firebaseConfig); const db = getDatabase(app); const auth = getAuth(app); const name = document.getElementById('nameInp'); const email = document.getElementById('emailInp'); const username = document.getElementById('userInp'); const pass = document.getElementById('passInp'); const submit = document.getElementById('sub_btn'); function isEmptyOrSpaces(str){ return str == null || str.match(/^ *$/) !== null; } function validation(){ const nameregex = /^[a-zA-Z\s]+$/; // 允许名字包含空格 const emailregex = /^[a-zA-Z0-9._%+-]+@(gmail|yahoo|outlook)\.com$/; const userregex = /^[a-zA-Z0-9]{5,}$/; if(isEmptyOrSpaces(name.value) || isEmptyOrSpaces(email.value) || isEmptyOrSpaces(username.value) || isEmptyOrSpaces(pass.value)){ alert("所有字段不能为空"); return false; } if (!nameregex.test(name.value)){ alert("姓名只能包含字母和空格!"); return false; } if(!emailregex.test(email.value)){ alert("请输入有效的邮箱地址!"); return false; } if(!userregex.test(username.value)){ alert("-用户名至少5个字符\n-用户名不能包含空格"); return false; } return true; } function RegisterUser(){ if (!validation()){ return; }; const dbRef = ref(db); get(child(dbRef, `UsersList/${username.value}`)).then((snapshot)=>{ if(snapshot.exists()){ alert("该用户名已存在"); } else { createUserWithEmailAndPassword(auth, email.value, pass.value) .then((userCredential) => { const user = userCredential.user; return set(ref(db, `UsersList/${username.value}`), { fullname: name.value, email: email.value, username: username.value, uid: user.uid }); }) .then(()=>{ alert("用户注册成功"); // 可选:跳转到登录页 window.location.href = "login.html"; }) .catch((error)=>{ alert(`错误:${error.message}`); }); } }).catch((error)=>{ alert(`数据库查询错误:${error.message}`); }); } submit.addEventListener('click', RegisterUser); </script> </body> </html>
内容的提问来源于stack exchange,提问作者Jonathan Marquez
相关产品推荐
相关产品推荐

