
前面介紹了 Firebase 的操作與資料存取以及透過 Express 框架讓 Node.js 使用上更友善後,終於要來把兩者結合準備設計屬於自己的 RESTful API 了!
Express 串接 Firebase 起手式
首先先輸入以下程式碼:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| const express = require("express"); const app = express();
const bodyParser = require("body-parser");
Sapp.use(express.static("public"));
app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false }));
app.get("/", (req, res) => { res.render("index"); });
const port = process.env.port || 3000; app.listen(port);
|
進入 Firebase 取得 SDK 設定
再來進到 Firebase 頁面左側工具列,有一個專案總覽選項,點擊旁邊的齒輪圖示,選取專案設定,最後在上方標籤列處選取服務帳戶。
專案總攬 > 專案設定 > 服務帳戶


此時會出現一個視窗會有四個選項,選擇 Node.js 項目,並且複製 Admin SDK 提供的程式碼,將其複製並貼上在本機的 app.js
中。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| const express = require("express"); const app = express();
const bodyParser = require("body-parser");
var admin = require("firebase-admin"); var serviceAccount = require("path/to/serviceAccountKey.json"); admin.initializeApp({ credential: admin.credential.cert(serviceAccount), databaseURL: "https://nodejsproject-d099d-default-rtdb.firebaseio.com", });
app.use(express.static("public"));
app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false }));
app.get("/", (req, res) => { res.render("index"); });
const port = process.env.port || 3000; app.listen(port);
|
下載金鑰
複製完程式碼後,在視窗最下方有一個藍色按鈕【產生新的私密金鑰】(如下圖)
firebase

,其金鑰就是保護資料不會被自己以外的來讀取此資料庫資料,點選後會下載到專案的根目錄下(或是想要指定存放的資料夾也可以),將檔名複製後,取代變數 serviceAccount 裡面的連結(如上方程式碼註解處)。
確認 Express 整合 firebase 服務
既然有引入套件,當然就要來安裝這些新增的程式,這邊有引入body-parser
跟 firebase-admin
,故輸入:
1
| npm install -D body-parser firebase-admin
|
安裝完後在剛剛複製的程式碼的下方打上以下程式碼:
javascript
1 2
| let fireData = admin.database(); console.log(fireData);
|
然後終端機啟動 node app.js,如果看到下方資訊:
terminal

以上就可以取得 firebase 的服務了!