注册表单无法向Firebase实时数据库写入数据,求解决方法
Firebase实时数据库无法接收注册表单数据排查
我对Firebase不太熟悉,想请教为何我编写的这个简单注册表单无法将数据发送到Firebase实时数据库。我已经尝试更换不同版本的Firebase、将实时数据库的读写权限设置为true,还新建了数据库,但问题依旧存在。
代码如下:
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <title>Hello, world!</title> </head> <body> <form id="mainForm" class="w-25 m-4"> <h2 class="mb-3">Register User</h2> <div class="form-floating mb-3"> <input type="email" class="form-control" id="emailInput" placeholder="name@example.com"> <label for="floatingInput">Email address</label> </div> <div class="form-floating mb-3"> <input type="password" class="form-control" id="passwordInput" placeholder="Password"> <label for="floatingPassword">Password</label> </div> <div class="form-floating mb-3"> <input type="text" class="form-control" id="usernameInput" placeholder="Username"> <label for="usernameInput">Username</label> </div> <button type="submit" class="btn btn-primary" style="float: right;">Create New User</button> <a href="login.html"><button type="button" class="btn btn-primary me-2" style="float: right;">Log Into Existing Account</button></a> </form> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> <script type="module"> import { getAnalytics } from "https://www.gstatic.com/firebasejs/10.7.1/firebase-analytics.js"; import { initializeApp } from "https://www.gstatic.com/firebasejs/10.7.1/firebase-app.js"; import { getDatabase, set,ref } from "https://www.gstatic.com/firebasejs/10.7.1/firebase-database.js"; import { getAuth, createUserWithEmailAndPassword } from "https://www.gstatic.com/firebasejs/10.7.1/firebase-auth.js"; const firebaseConfig = { apiKey: "AIzaSyCldJtrt23-mz3CIubgwGc02tzJxfRoHa8", authDomain: "fitforged-b9d11.firebaseapp.com", projectId: "fitforged-b9d11", storageBucket: "fitforged-b9d11.appspot.com", messagingSenderId: "618367077709", appId: "1:618367077709:web:5a5517cab12a9271963b04", measurementId: "G-ZY3NK4ZT38" }; const app = initializeApp(firebaseConfig); const analytics = getAnalytics(app); const db = getDatabase(app); const auth = getAuth(app); let emailInput=document.getElementById('emailInput'); let passwordInput=document.getElementById('passwordInput'); let usernameInput=document.getElementById('usernameInput'); let mainForm=document.getElementById('mainForm'); let RegisterUser = evt =>{ evt.preventDefault(); createUserWithEmailAndPassword(auth, emailInput.value,passwordInput.value) .then((credentials)=>{ const user = credentials.user; set(ref(db,'users/'+user.uid),{ username: usernameInput.value, email: emailInput.value, }) console.log(credentials); window.location.href='home.html'; alert("successfully created user"); }) .catch((error)=>{ alert(error.message); console.log(error.message); }) } mainForm.addEventListener('submit',RegisterUser); </script> </body> </html>
可能的问题及解决办法
- 异步操作未等待完成就跳转:你当前在调用
set写入数据库后,立刻执行window.location.href='home.html',这会直接终止页面的所有异步请求,包括未完成的数据库写入。需要等待set操作完成后再执行跳转和提示:
let RegisterUser = evt =>{ evt.preventDefault(); createUserWithEmailAndPassword(auth, emailInput.value,passwordInput.value) .then((credentials)=>{ const user = credentials.user; // 返回set的Promise,让后续then等待写入完成 return set(ref(db,'users/'+user.uid),{ username: usernameInput.value, email: emailInput.value, }) }) .then(() => { alert("successfully created user"); window.location.href='home.html'; }) .catch((error)=>{ alert(error.message); console.log(error.message); }) }
- 检查数据库地域与初始化配置:如果是新创建的实时数据库,可能需要在初始化数据库时指定对应的数据库URL(从Firebase控制台复制你的实时数据库完整URL),确保代码连接的是正确的数据库实例:
const db = getDatabase(app, "https://fitforged-b9d11-default-rtdb.xxxx.firebasedatabase.app/");
捕获数据库写入错误:原代码中
set操作的错误没有被捕获,修改后的代码将set的Promise返回,统一在catch中处理auth和数据库的所有错误,打开浏览器开发者工具的Console标签,就能看到具体的失败原因。确认表单输入有效:可以在函数开头添加日志,确认输入框的值是否正确获取:
let RegisterUser = evt =>{ evt.preventDefault(); console.log("Username:", usernameInput.value, "Email:", emailInput.value); // 后续代码... }
内容的提问来源于stack exchange,提问作者George05
相关产品推荐
相关产品推荐

