串接Firebase基本教學
是否有在第一次串接Firebase的database時,明明照著步驟做卻一直失敗的經驗?這裡提供簡易的範例。
這裡的寫法是在 script module type 引入 CDN。並且使用的是 Realtime Database
Realtime Database
這個資料庫的格式就跟JSON一樣,你可以在存進資料時設定欄位路徑,像是 all/member
。
資料上傳
除了要注意Firebase免費的Spark方案的每日流量和同時訪問數的限制之外,還要注意write和read的權限設定。
// Import the functions you need from the SDKs
import { initializeApp } from "https://www.gstatic.com/firebasejs/11.1.0/firebase-app.js";
import { getDatabase, ref, push, set } from "https://www.gstatic.com/firebasejs/11.1.0/firebase-database.js";
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "*********",
authDomain: "專案id.firebaseapp.com",
projectId: "專案id",
storageBucket: "專案id.firebasestorage.app",
messagingSenderId: "123456789",
appId: "123456789:web:f96e474ce78f56f78a509f"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const database = getDatabase(app);
// Function to write data to Firebase
async function saveNumberToFirebase(number) {
const numbersRef = ref(database, 'numbers'); // firebase的資料庫欄位路徑名稱
const newNumberRef = push(numbersRef);
await set(newNumberRef, { number: number });
alert('Number saved successfully!');
}
// submit form data
document.getElementById('the-form').addEventListener('submit', function(event) {
event.preventDefault();
const numberValue = document.getElementById('work-number').value;
saveNumberToFirebase(numberValue);
});
讀取資料
// Import the functions you need from the SDKs
import { initializeApp } from "https://www.gstatic.com/firebasejs/11.1.0/firebase-app.js";
import { getDatabase, ref, get, child } from "https://www.gstatic.com/firebasejs/11.1.0/firebase-database.js";
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "*********",
authDomain: "專案id.firebaseapp.com",
projectId: "專案id",
storageBucket: "專案id.firebasestorage.app",
messagingSenderId: "123456789",
appId: "123456789:web:f96e474ce78f56f78a509f"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const database = getDatabase(app);
// read data from Firebase and create li tag to show data
async function fetchNumbersFromFirebase() {
const dbRef = ref(database);
const snapshot = await get(child(dbRef, 'numbers')); // firebase的資料庫欄位路徑名稱
if (snapshot.exists()) {
const numbersList = document.getElementById('numbers-list');
const totalNumber = document.createElement('div');
let count = 0;
snapshot.forEach(childSnapshot => {
count++;
const listItem = document.createElement('li');
listItem.textContent = `${childSnapshot.val().number}`;
numbersList.appendChild(listItem);
});
totalNumber.textContent = `Total numbers: ${count}`;
document.body.insertBefore(totalNumber, document.body.firstChild);
} else {
alert('No data available');
}
}
fetchNumbersFromFirebase();
如果你沒有地方存資料,而且流量與容量不大的話,Firebase是個好選擇。而如果資料比較敏感需要保密的話,還要再設定Firebase裡面的auth功能。
留言
張貼留言