简体   繁体   English

可以用firebase和快递一起用吗?

[英]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.我是新手,我想从 express.js 构建一个 rest api,它使用 firebase 作为数据库。 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.当我 go 到“端口:3500”时,服务器停止响应我听说云 function 但我们需要为此付费。 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.问题是您仅在请求 api 时读取数据,并且您没有发送响应。 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.用此代码替换您的 app.get,它应该可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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