Не работает аутентификация в firebase
Я новичок в JS и Firebase, так что сильно не пинайте Следующий код должен должен захватить имя пользователя и пароль и передать его в firebase, но выдает такую ошибку Uncaught TypeError: Cannot read property 'addEventListener' of null at auth.js:24 Что же не так?
Код на HTML
<card class="auth">
<h1 class="auth-title">Auth</h1>
<h2 class="auth-text">Enter an email and password below to sign up or log in</h2>
<input id="txtEmail" type="email" name="email" placeholder="Email" required class="input-field">
<input id="txtPassword" type="password" name="password" placeholder="Password" required class="input-field">
<button class="medium-button auth-title" id="btnLogin" type="submit" autofocus>Log In</button>
<button class="medium-button auth-title" id="btnSignUp" type="submit" autofocus>Sign Up</button>
</card>
Код на JS
const txtEmail = document.getElementById("txtEmail");
const txtPassword = document.getElementById("txtPassword");
const btnSignUp = document.getElementById("btnSignUp");
const btnLogin = document.getElementById("btnLogin");
btnLogin.addEventListener('click', e => {
const email = txtEmail.value;
const pass = txtPassword.value;
const auth = firebase.auth();
const promise = auth.signInWithEmailAndPassword(email, pass);
promise.catch(e => console.log(e.message));
});
btnSignUp.addEventListener('click', e => {
const email = txtEmail.value;
const pass = txtPassword.value;
const auth = firebase.auth();
const promise = auth.createUserWithEmailAndPassword(email, pass);
promise.catch(e => console.log(e.message));
});
firebase.auth().onAuthStateChanged(firebaseUser =>{
if (firebaseUser) {
console.log(firebaseUser)
} else {
console.log("not logged in");
}
});
Ответы (1 шт):
Автор решения: Роман Мереняну-Ени
→ Ссылка
На лицо, что выполняется код до загрузки страницы. Попробуйте или проверку до события или онлоад на загрузку страницы.
const btnLogin = document.getElementById("btnLogin");
if(btnLogin ){
btnLogin.addEventListener('click', e => {
const email = txtEmail.value;
const pass = txtPassword.value;
const auth = firebase.auth();
const promise = auth.signInWithEmailAndPassword(email, pass);
promise.catch(e => console.log(e.message));
});
}
window.onload=function(){
и ваш код..
}