安裝及在 JavaScript 中設定

Firebase 即時資料庫是一個雲端託管資料庫。資料以 JSON 形式儲存並即時同步到每個連接的客戶端。當您使用我們的 Android、Apple 平台和 JavaScript SDK 建立跨平台應用程式時,您的所有用戶端都會共用一個即時資料庫實例,並自動接收最新資料的更新。

先決條件

如果您尚未安裝 Firebase JS SDK 並初始化 Firebase

建立資料庫

  1. 導覽至Firebase 控制台「即時資料庫」部分。系統會提示您選擇現有的 Firebase 專案。遵循資料庫建立工作流程。

  2. 選擇 Firebase 安全性規則的啟動模式:

    測試模式

    適合開始使用行動和 Web 用戶端庫,但允許任何人讀取和覆蓋您的資料。測試後,請務必查看了解 Firebase 即時資料庫規則部分。

    若要開始使用 Web、Apple 或 Android SDK,請選擇測試模式。

    鎖定模式

    拒絕來自行動和 Web 用戶端的所有讀取和寫入。經過身份驗證的應用程式伺服器仍然可以存取您的資料庫。

  3. 選擇資料庫的位置。

    根據資料庫的位置,新資料庫的 URL 將採用以下形式之一:

    • DATABASE_NAME .firebaseio.com (適用於us-central1中的資料庫)

    • DATABASE_NAME . REGION .firebasedatabase.app (適用於所有其他位置的資料庫)

  4. 按一下“完成”

啟用即時資料庫時,也會啟用Cloud API Manager中的 API。

配置即時資料庫安全規則

即時資料庫提供了一種聲明性規則語言,可讓您定義資料的結構方式、索引的方式以及何時可以讀取和寫入資料。

新增即時資料庫JS SDK並初始化即時資料庫

初始化 JavaScript SDK 時,您必須指定即時資料庫 URL。

您可以在Firebase 控制台的「即時資料庫」部分找到您的即時資料庫 URL。根據資料庫的位置,資料庫 URL 將採用以下形式之一:

  • https:// DATABASE_NAME .firebaseio.com (適用於us-central1中的資料庫)
  • https:// DATABASE_NAME . REGION .firebasedatabase.app (適用於所有其他位置的資料庫)

使用以下程式碼片段初始化 SDK:

網路模組化API

import { initializeApp } from "firebase/app";
import { getDatabase } from "firebase/database";

// TODO: Replace the following with your app's Firebase project configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
  // ...
  // The value of `databaseURL` depends on the location of the database
  databaseURL: "https://DATABASE_NAME.firebaseio.com",
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);


// Initialize Realtime Database and get a reference to the service
const database = getDatabase(app);

Web 命名空間 API

import firebase from "firebase/app";
import "firebase/compat/database";

// TODO: Replace the following with your app's Firebase project configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
  // ...
  // The value of `databaseURL` depends on the location of the database
  databaseURL: "https://DATABASE_NAME.firebaseio.com",
};

// Initialize Firebase
firebase.initializeApp(firebaseConfig);


// Initialize Realtime Database and get a reference to the service
const database = firebase.database();

您已準備好開始使用 Firebase 即時資料庫!

下一步