gpt4 book ai didi

javascript - 向数据库添加数据时出现的问题

转载 作者:行者123 更新时间:2023-12-02 13:51:15 25 4
gpt4 key购买 nike

我的问题是通过从表单中获取信息来将数据添加到数据库中。我想将信息添加为“名称”。我可以正确添加“电子邮件”,但不能正确添加其他数据。

我的代码:

buttonsignup.addEventListener('click', error => {
var nameCompany = document.getElementById('nameCompany').value;
var email = document.getElementById('email').value;
});

function add(nameCompany,email) {
firebase.database().ref().child('users_company').push({
nameCompany: nameCompany,
email: email
});
}


function intFirebase () {

/*CURRENT USER*/
firebase.auth().onAuthStateChanged(function(user) {
if (user != null) {
console.log(user);
console.log('El UID es '+user.uid);
add(nameCompany,user.email);
} else {
console.log('No user is signed in.');
}
});
}

window.onload = function() {
intFirebase();
}

好的,把咖啡变成代码之后。我找到了这个解决方案。但是......这是一个好的做法吗?

const database = firebase.database();
var user = firebase.auth().currentUser;

/* BOTON SIGNUP */

buttonsignup.addEventListener('click', error => {

var nameCompany = document.getElementById('nameCompany').value;
var email = document.getElementById('email').value;
var password_1 = document.getElementById('password_1').value;
var password_2 = document.getElementById('password_2').value;

if (password_1 == password_2) {
if (password_1.length < 8) {
console.log('Contraseña muy corta');
document.getElementById("errorPassword").innerHTML = "8 characters";
} else {
firebase.auth().createUserWithEmailAndPassword(email, password_1).then (function(result) {
add(nameCompany,email);
}).catch(function (error) {
var errorCode = error.code;
var errorMessage = error.message;
};
});
}
} else{
console.log('errorPassword');
}
});

function add(nameCompany,email) {
firebase.database().ref().child('users_company').push({
nameCompany: nameCompany,
emailCompany: email
});
}


function intFirebase () {

/*CURRENT USER*/
firebase.auth().onAuthStateChanged(function(user) {
if (user != null) {
console.log(user);
console.log('El UID es '+user.uid);
} else {
console.log('No user is signed in.');
}
});
}

window.onload = function() {
intFirebase();
}

和数据库规则

{
"rules": {
"users_company": {
"$uid": {
".read": "auth != null && auth.uid === $uid",
".write": true,
//Change this code to: I can not do scripts in the database. -> ".write": "auth != null && auth.uid === $uid",
"nameCompany" : {
".validate": "newData.isString() && newData.val().length < 100"
},
"emailCompany" :{
".validate": "newData.isString() && newData.val().length < 100"
}
}
}
}
}

最佳答案

在您的 intFirebase 函数中,只有当前用户已经登录时,您才会调用数据库。您的电子邮件正常工作的原因只是因为您正在使用“user.email”,在它看到用户确实是已登录。

如果您正在尝试创建一个新用户(我认为这就是顶部的事件监听器正在尝试执行的操作),那么您应该在提交表单时将添加函数移至触发。

关于javascript - 向数据库添加数据时出现的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40987015/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com