Firebase数据库写入报错:‘firebase is not defined’问题求助
解决Firebase v9中"firebase is not defined"数据库操作错误
问题原因
你使用的是Firebase v9模块化SDK,但数据库操作代码仍沿用旧版命名空间风格的firebase.database()调用——v9中已移除全局firebase对象,必须通过导入的模块化方法结合初始化的数据库实例完成操作。
修复步骤
- 补充导入数据库操作方法:从
firebase-database中导入ref(创建数据库引用)和set(写入数据)方法 - 替换旧引用方式:用初始化好的
database实例配合ref方法,替代firebase.database().ref() - 修正时间戳写法:
Date.now是函数,需改为Date.now()才能获取当前时间戳 - 安全修正:不要将明文密码存入数据库,Firebase Auth会自动安全存储用户凭证,明文存储存在严重安全风险
修改后的完整代码
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.13.0/firebase-app.js"; import { getAuth, createUserWithEmailAndPassword } from "https://www.gstatic.com/firebasejs/9.13.0/firebase-auth.js"; // 补充导入数据库操作所需方法 import { getDatabase, ref, set } from "https://www.gstatic.com/firebasejs/9.13.0/firebase-database.js"; const firebaseConfig = { apiKey: "AIzaSyCQjuF9A4Km_M7Eo5gnd1B6nmDRRYSle2c", authDomain: "badge-world.firebaseapp.com", projectId: "badge-world", storageBucket: "badge-world.appspot.com", messagingSenderId: "186421361260", appId: "1:186421361260:web:852bcaa237f86a76b1f649" }; const app = initializeApp(firebaseConfig); const auth = getAuth(app); const database = getDatabase(app); document.getElementById ("signup-button").addEventListener("click", register); document.getElementById ("login-button").addEventListener("click", login); function register() { let email = document.getElementById('email').value let password = document.getElementById('password').value let username = document.getElementById('username').value if (validate_email(email) == false || validate_password(password) == false) { alert("Incorrect Fields. Remember password has to have more than 6 characters and there must be a valid email.") return; // 验证不通过时终止后续执行 } if(validate_field(username) == false) { alert("Username missing") return; // 验证不通过时终止后续执行 } createUserWithEmailAndPassword(auth, email, password) .then(function (){ const user = auth.currentUser // 使用模块化方式创建数据库引用 const userRef = ref(database, 'users/' + user.uid); const user_data = { email : email, username: username, last_login : Date.now() // 修正为调用函数获取时间戳 } // 使用set方法写入数据 set(userRef, user_data) .then(() => { alert("User Created!") }) .catch((dbError) => { alert("Database write error: " + dbError.message) }) }) .catch(function(error) { const error_code = error.code const error_message = error.message alert(error_message) }) } function login() { } // Validate Functions function validate_email(email) { let expression = /^[^@]+@\w+(\.\w+)+\w$/ if (expression.test(email) == true) { return true } else { return false } } function validate_password(password) { // 修正判断逻辑:字符串需判断长度而非直接与数字比较 if (password.length < 6) { return false } else { return true } } function validate_field(field) { if (field == null || field.length <= 0) { return false } else { return true } }
额外优化点
- 验证不通过时添加
return语句,避免无效代码执行 - 修正
validate_password的判断逻辑(原代码字符串与数字比较会出错) - 为数据库写入单独添加错误捕获,便于区分Auth错误和数据库错误
内容的提问来源于stack exchange,提问作者pizzalawl
相关产品推荐
相关产品推荐

