前言 專案已經建立了,資料庫也準備好了,接下來就是準備基礎認識 Firebase 囉
建立 Project 首先建立一個 index.html、all.js,而 index.html 內容如下(包含 Firebase SDK 金鑰)
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 27 28 29 30 31 32 33 <!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <meta name ="viewport" content ="width=device-width, initial-scale=1.0" > <meta http-equiv ="X-UA-Compatible" content ="ie=edge" > <title > Document</title > </head > <body > <script src ="https://www.gstatic.com/firebasejs/6.2.4/firebase-app.js" > </script > <script > var firebaseConfig = { apiKey: "AIzaSyAd3vTBFRS7o3NuyEubF7JaF-Xc1U7EoAQ" , authDomain: "testproject-b5784.firebaseapp.com" , databaseURL: "https://testproject-b5784.firebaseio.com" , projectId: "testproject-b5784" , storageBucket: "" , messagingSenderId: "120474895761" , appId: "1:120474895761:web:33b6ff0885191e8d" }; firebase.initializeApp(firebaseConfig); </script > <script src ="./all.js" > </script > </body > </html >
測試是否有接上 Firebase 接下來就是要測試是否有接上 Firebase,所以這邊試著在 all.js 輸入 firebase.database()
,不意外你會遇到這個錯誤 (TypeError: firebase.database is not a function
)
這個原因是出在 2019 / 5 左右 Firebase 將一些檔案拆出來了,所以這邊要在加載一個 CDN
(<script src="https://www.gstatic.com/firebasejs/5.10.1/firebase-database.js"></script>
)
所以這時候 HTML 結構會變成這樣子
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 27 28 29 <!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <meta name ="viewport" content ="width=device-width, initial-scale=1.0" > <meta http-equiv ="X-UA-Compatible" content ="ie=edge" > <title > Document</title > </head > <body > <script src ="https://www.gstatic.com/firebasejs/6.2.4/firebase-app.js" > </script > <script src ="https://www.gstatic.com/firebasejs/5.10.1/firebase-database.js" > </script > <script > var firebaseConfig = { apiKey: "AIzaSyAd3vTBFRS7o3NuyEubF7JaF-Xc1U7EoAQ" , authDomain: "testproject-b5784.firebaseapp.com" , databaseURL: "https://testproject-b5784.firebaseio.com" , projectId: "testproject-b5784" , storageBucket: "" , messagingSenderId: "120474895761" , appId: "1:120474895761:web:33b6ff0885191e8d" }; firebase.initializeApp(firebaseConfig); </script > <script src ="./all.js" > </script > </body > </html >
這時候你再重新整理應該會發現並不會任何錯誤訊息了,所以這邊 all.js
要稍作一下調整
1 console .log(firebase.database());
這時候再重新整理一次就可以成功接上 Firebase 哩