Аутентификация Firebase (электронная почта и пароль) не аутентифицируется - PullRequest
0 голосов
/ 02 мая 2019

Я не могу заставить работать firebase auth. В БД включена аутентификация пользователя и создан логин. Когда используется консоль отладки браузера, появляется только 1 предупреждение:

It looks like you're using the development build of the Firebase JS SDK.
When deploying Firebase apps to production, it is advisable to only import the individual SDK components you intend to use.

Я не уверен, что мне здесь не хватает. любая помощь с благодарностью.

function login(){

    const userEmail = document.getElementById('userEmail');
    const userPassword = document.getElementById('userPassword');
    const loginBtn = document.getElementById('loginBtn');

    loginBtn.addEvenListener('click'), e => {
      const email = userEmail.value;
      const pass = userPassword.value;
}
  firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
        var errorCode = error.code;
        var errorMessage = error.message;
        if (errorCode === 'auth/wrong-password') {
          alert('Wrong password.');
        } else {
          alert(errorMessage);
        }
        console.log(error);
    });
    firebase.auth().onAuthStateChanged(user => {
          if (user) {
            window.location = 'secondpage.html';
          }
        });
  }
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
<h1>TESTING</h1>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="author" content="Name"
<link rel="stylesheet" href="style.css" />
</head>

<body>
<div id="login_div" class="main-div">
<h3>Welcome</h3>
<input id="userEmail" type="email" placeholder="Email..." />
<input id="userPassword" type="password" placeholder="Password..." />

<button click="login()">Login to Account</button>
</div>

<script src="https://www.gstatic.com/firebasejs/5.11.0/firebase.js"></script>
   <script>
  // Initialize Firebase
    var config = {
    apiKey: "KEY",
    authDomain: "name.firebaseapp.com",
    databaseURL: "https://name.firebaseio.com",
    projectId: "testlist",
    storageBucket: "testlist.appspot.com",
    messagingSenderId: "111111111111"
    };
    firebase.initializeApp(config);
    </script>

    <script src="test.js"></script>
    </body>
  </html>

Ответы [ 2 ]

0 голосов
/ 02 мая 2019

Вы используете неправильный скрипт. Вы используете:

<script src="https://www.gstatic.com/firebasejs/5.11.0/firebase.js"></script>

Но вам нужно использовать:

<script src="https://www.gstatic.com/firebasejs/5.11.0/firebase-app.js"></script>

На многих форумах указывалось, что один / firebase выдает эту ошибку, так как вам нужен / firebase-app. Просто получить Firebase One, вероятно, импортирует намного больше, чем вам нужно, и это увеличивает размер вашего приложения

Также для вашей аутентификации вам, вероятно, также понадобится:

<script src="https://www.gstatic.com/firebasejs/5.11.0/firebase-auth.js"></script>


<script src="https://www.gstatic.com/firebasejs/5.11.0/firebase-database.js"></script>
0 голосов
/ 02 мая 2019

попробуйте этот код!

проблема с вашей кнопкой.

<button click="login()">Login to Account</button>

click не является допустимым событием, onclick является действительным.поэтому ваша кнопка будет выглядеть так:

<button onclick="login()">Login to Account</button>
<html>
<head>
<title>TEST</title>
<h1>TESTING</h1>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="author" content="Name"
<link rel="stylesheet" href="style.css" />
</head>

<body>
<div id="login_div" class="main-div">
<h3>Welcome</h3>
<input id="userEmail" type="email" placeholder="Email..." />
<input id="userPassword" type="password" placeholder="Password..." />

<button onclick="login()">Login to Account</button>
</div>

<script src="https://www.gstatic.com/firebasejs/5.11.0/firebase.js"></script>
   <script>
//   Initialize Firebase
    var config = {
    apiKey: "KEY",
    authDomain: "name.firebaseapp.com",
    databaseURL: "https://name.firebaseio.com",
    projectId: "testlist",
    storageBucket: "testlist.appspot.com",
    messagingSenderId: "111111111111"
    };
    firebase.initializeApp(config);
  firebase.initializeApp(config);
    </script>

    <script src="test.js"></script>
    </body>
  </html>

<_TEST.js-> 


function login() {
  const userEmail = document.getElementById("userEmail");
  const userPassword = document.getElementById("userPassword");

  const email = userEmail.value;
  console.log("TCL: login -> email", email);
  const pass = userPassword.value;
  console.log("TCL: login -> pass", pass);

  firebase
    .auth()
    .signInWithEmailAndPassword(email, pass)
    .catch(function(error) {
      var errorCode = error.code;
      var errorMessage = error.message;
      if (errorCode === "auth/wrong-password") {
        alert("Wrong password.");
      } else {
        alert(errorMessage);
      }
      console.log(error);
    });
  firebase.auth().onAuthStateChanged(user => {
    console.log("TCL: login -> user", user);
    if (user) {
       window.location = "secondpage.html";
    }
  });
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...