我正在尝试使用firebase设计一个简单的登录系统。
这是我的app.js下面的代码,其中包含用于登录,注册和注销的功能。
(function(){
// Initialize Firebase
var config = {
apiKey: "Apikey",
authDomain: "login-8a262.firebaseapp.com",
databaseURL: "firebasedb url",
projectId: "login-8a262",
storageBucket: "login-8a262.appspot.com",
messagingSenderId: "737178664611"
};
firebase.initializeApp(config);
//Get all the elements
const txtEmail= document.getElementById('txtEmail');
const txtPassword= document.getElementById('txtPassword');
const btnLogin= document.getElementById('btnLogin');
const btnSignUp= document.getElementById('btnSignUp');
const btnLogout= document.getElementById('btnLogout');
//Add the Login Event
btnLogin.addEventListener('click', e=>{
//Get the email and password
const email = txtEmail.value;
const pass = txtPassword.value;
const auth = firebase.auth();
//Sign in
const promise = auth.signInWithEmailAndPassword(email, pass);
promise.catch(e => console.log(e.message));
});
//Add the signup event
btnSignUp.addEventListener('click', e=>{
console.log('in signup now');
//Get the email and password
const email = txtEmail.value;
const pass = txtPassword.value;
const auth = firebase.auth();
//Sign in
const promise = auth.createUserWithEmailAndPassword(email, pass);
promise.catch(e => console.log(e.message));
});
btnLogout.addEventListener('click', e=>{
firebase.auth().signOut();
});
//Add a realtime listener
firebase.auth().onAuthStateChanged(firebaseUser => {
if(firebaseUser)
{
console.log(firebaseUser);
btnLogout.classList.remove('hide');
}
else
{
console.log(firebaseUser);
console.log('not logged in');
btnLogout.classList.add('hide');
}
});
}());
以下是我的html代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> Firebase Web Quickstart</title>
<link
href="https://fonts.googleapis.com/css?family=Roboto:300,500" rel="stylesheet">
<script src="https://www.gstatic.com/firebasejs/4.6.2/firebase.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="app.js"></script>
</head>
<body>
<div class="container">
<input id="txtEmail" type="email" placeholder="Email">
<input id="txtPassword" type="Password"
placeholder="Password">
<button id="btnLogin" class="btn btn-action">
Log in
</button>
<button id="btnSignUp" class="btn btn-secondary">
Sign Up
</button>
<button id="btnLogout" class="btn btn-action hide">
Log Out
</button>
</div>
</body>
</html>
我无法弄清楚为什么我会为addEventListener方法获得以下错误。
未捕获的TypeError:无法读取属性&#39; addEventListener&#39;为null 在app.js:23 在app.js:70
答案 0 :(得分:0)
您需要添加firebase sdk脚本。
<script src="//www.gstatic.com/firebasejs/4.6.2/firebase.js"></script>
<script src="//www.gstatic.com/firebasejs/4.6.0/firebase-firestore.js"></script>
<script src="your-script.js"></script>
</body>