简体   繁体   中英

Is it possible to use firebase and express together?

I am new to express and i wanted to build a rest api from express.js that uses firebase as database. is it possible for them to work together? i tried doing this...

 const firebase = require("firebase") const express = require("express"); const app = express(); const cors = require( 'cors'); var firebaseConfig = { apiKey: "xxxxxxx", authDomain: "xxxxxx", databaseURL: "xxxxxx", projectId: "xxxxxx", storageBucket: "xxxxxx", messagingSenderId: "xxxxxx", appId: "xxxxxxx" }; // Initialize Firebase firebase.initializeApp(firebaseConfig); app.use(cors()) let data; firebase.database().ref("public").on("value", snapshot =>{ data = snapshot.val(); }) app.get("/api", (req, res)=>{ res.send(data) }) app.listen(3500, ()=>console.log("listening at port 3500..."))

But it didnt work, the server keeps on disconnecting, the server does not respond and i have to start it again. And when i go to "port: 3500" the server stops responding I heard about cloud function but we need pay for it. Is there any other way?

The issue is that you're only reading the data when the api is requested, and you aren't sending a response. Here's how I fixed it:

firebase.database().ref("public").on("value", snapshot =>{
data = snapshot.val();
})

app.get("/api", (req, res)=>{
    res.send(data)

})

Replace your app.get with this code, and it should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM