首页 > 文章列表 > Firebase 与 Web 集成

Firebase 与 Web 集成

225 2023-09-15

Firebase 由 Google 于 2014 年推出,为其用户提供后端服务。它提供了不同类型的高质量服务,我们可以使用这些服务来开发移动和网络应用程序。例如,它提供实时数据库、用户身份验证、云存储等。此外,它还提供分析功能来分析应用程序的流量。由于其快速设置而更受欢迎。

在本教程中,我们将学习如何将 Firebase 身份验证集成到单页 Web 应用程序中。

用户应按照以下步骤设置 Firebase 帐户并将其与单页 Web 应用程序集成。

  • 第 1 步 - 首先,访问 Firebase 网站并创建一个帐户。

  • 第 2 步 - 现在,转到 https://console.firebase.google.com/u/0/ 打开 Firebase 控制台。

  • 第 3 步 - 现在,单击“创建项目”按钮开始创建新项目。

Firebase 与 Web 集成

  • 第 4 步 - 在此填写所需的详细信息,然后单击“继续”按钮。我们正在此处创建一个“测试”应用程序。

Firebase 与 Web 集成

  • 第 5 步 - 选择首选位置,接受条款和条件,然后单击“创建项目”按钮。之后,请等待它为您创建一个项目。

Firebase 与 Web 集成

  • 第 6 步 - 它会将您重定向到以下页面。在这里,单击“身份验证”卡元素。之后,单击“开始”按钮。

Firebase 与 Web 集成

  • 第 7 步 - 转到“登录方法”选项卡,然后单击“电子邮件/密码”字段。之后,启用“电子邮件/密码”方法,然后单击“保存”按钮。用户还可以从此处启用其他方式来验证您的 Web 应用程序。

Firebase 与 Web 集成

  • 第 8 步 - 现在,单击“项目设置”并从那里获取 API 和项目 ID。将其存放在某处。我们将在下面的示例中使用它。

Firebase 与 Web 集成

创建单页静态应用程序

现在,Firebase 项目的设置已完成。接下来,我们将创建一个单页静态应用程序。

步骤

  • 第 1 步 - 以任一方式将 Firebase 添加到您的项目中。这里,我们添加了使用CDN。开发者也可以根据自己当前从事的项目使用该SDK。

  • 步骤 2 - 现在,构建一个简单的 HTML 模板来输入电子邮件和密码。另外,添加注册、登录和注销按钮。

  • 第 3 步 - 在 JavaScript 中,使用 API 密钥和项目 ID 初始化 Firebase 配置。

  • 步骤 4 - 使用 onAuthStateChanged() 方法在身份验证状态更改时打印消息。

  • 第 5 步 - 使用 Firebase 的 auth() 方法初始化身份验证。

  • 第 6 步 - 现在,创建一个 addUsers() 函数以将用户添加到 Firebase。在函数中访问电子邮件和密码,并使用 createUserWithEmailAndPassword() 方法将用户添加到 Firebase。

  • 第7步 - 现在,创建一个logIn()函数,并使用signInWithEmailAndPassword()方法使用电子邮件和密码登录应用程序。

  • 第 8 步 - 另外,创建一个 logout() 函数,它使用 signOut() 方法来结束当前会话。

示例

在下面的示例中,我们创建了一个带有两个输入字段的简单表单。每当用户单击注册按钮时,它都会调用 addUsers() 函数,该函数将用户添加到 Firebase。如果用户输入弱密码或错误的电子邮件地址,Firebase 将返回错误。

此外,当用户单击登录按钮时,它会调用“login()”函数,该函数允许用户登录应用程序。如果用户输入错误的密码或电子邮件,Firebase 会返回错误。当用户单击signOut按钮时,它会执行signOut()函数,结束当前会话。

注意 - 这里,开发者需要根据他们的项目更改API密钥、项目ID和项目域。生成以下凭据仅用于测试目的。

<html>
<head>
   <script src = "https://www.gstatic.com/firebasejs/8.2.7/firebase-app.js">
   </script>
   <script src = "https://www.gstatic.com/firebasejs/8.2.7/firebase-auth.js">
   </script>
   <style>
      button {
         width: 100px;
         height: auto;
         padding: 5px 10px;
         background-color: aqua;
         border: 2px solid green;
         border-radius: 12px;
      }
   </style>
</head>
<body>
   <h2>
      Using the <i> Firebase auth </i> to add authentication in a single page static website.
   </h2>
   <div class = "container">
      <h2>Enter the email and password below.</h2>
      <input type = "email" placeholder = "abcd@gamil.com" id = "email" />
      <br /> <br />
      <input type = "password" placeholder = "Add password" id = "password" />
      <br /> <br />
      <button onclick = "addUsers()" id = "signUp">
         SignUp
      </button>
      <button onclick = "login()" id = "logIp">
         SignIn
      </button>
      <button onclick = "logout()" id = "logOut">
         SignOut
      </button>
      <br> <br>
      <div id = "output"> </div>
   </div>
   <script>
      let output = document.getElementById('output');
      // Your web app's Firebase configuration
      var initialConfig = {
         apiKey: "AIzaSyBsYILuhF4wOGOe0rFhPudhVWO3cGh2z18", // change API keu
         authDomain: "localhost", // change domain
         projectId: "test-application-45005", // change project Id
      };
      
      // Initialize Firebase
      firebase.initializeApp(initialConfig);
      const authenticate = firebase.auth();
      
      // Check if there are any active users
      firebase.auth().onAuthStateChanged((user) => {
         if (user) {
            var email = user.email;
            output.innerHTML = "Active user is " + email + "<br>";
         } else {
            output.innerHTML = "No active users" + "<br>";
         }
      });
      
      // add users
      function addUsers() {
         var email = document.getElementById("email").value;
         var password = document.getElementById("password").value;
         
         // adding users via the promise
         authenticate.createUserWithEmailAndPassword(
            email,
            password
         ).then((userCredential) => {
            output.innerHTML = "User added successfully and user id is " + userCredential.user.uid + "<br>";
         }).catch((e) => {
            output.innerHTML = "Some error occurred - " + e.message + "<br>";
         });
      }
      
      // login function
      function login() {
         var email = document.getElementById("email").value;
         var password = document.getElementById("password").value;
         authenticate.signInWithEmailAndPassword(
         email, password).then((userCredential) => {
            output.innerHTML = "User login successfully and user id is " + userCredential.user.uid + "<br>";
         }).catch((e) => {
            output.innerHTML = "Some error occurred - " + e.message + "<br>";
         });
      }
      
      // logout currently logged-in user
      function logout() {
         authenticate.signOut();
         output.innerHTML = "User logout successfully";
      }

   </script>
</body>
</html>

用户学会了如何将 Firebase 与 Web 应用程序集成。对于经验丰富的开发人员来说,将 Firebase 与任何 Web 应用程序集成几乎不需要 15 分钟。此外,如果用户在登录应用程序时输入弱密码,它会给出错误,并且它会管理开发人员无需担心的所有其他内容。

此外,开发者还可以将 Firebase 数据库与任何 Web 或移动应用程序一起使用。