I'm using express to deal with all the routing of my web app. I'm also using firebase to store all my data.
So I wanted to split my code like this:
index.js
: node app, routing and get data from firebase. Send data to the view(s).
index.html
: display my app (a view) and include client.js
client.js
: use the data from index.js
(firebase) and use it to generate a graph in index.html
.
I liked this structure because index.js
was in charge on the routing and getting the data, and index.html
and client.js
handled the display.
Unfortunately, this structure is not really working with Firebase. Since Firebase receive data at each modification of the DB, this code:
app.get('/moods/get', function(req, res){
moodRef.on('value', function(snapshot){
res.json(snapshot.val());
})
});
Display this error:
Error: Can't set headers after they are sent.
I think it's pretty obvious, the HTML page is already displayed, so trying to send json produces this error.
So what is the solution? Using firebase in client.js
so it can update in live the display, but my code structure becomes a bit weird.
client.js
is now in charge of the data, the display, and index.js
is only in charge of the routing?
What are the best practices? How would you organize your code for this kind of projects?
Thanks in advance.
With http, you cannot just send data to the client whenever you want. The client has to make a specific request and then you can return data from that request and only for the life of that request.
So, for http, you would have to field the http request to get some data and then do a query of the database to fetch the appropriate data that matches what the specific http request is asking for.
If you want to be able to just send data to the client whenever something changes, then you probably want to use a webSocket. With a webSocket, the client makes a connection to the server and keeps the connection alive and then either side can send messages to the other. In your particular instance, anytime something changes in the database, you could deliver that change to each connected client. When the client Javascript receives this change, it could then update the currently displayed page.
A common library for making webSockets easier is the socket.io library which works well with node.js. In this case, you would have on place in your code (not in a request handler) that listens for database changes and then when one happens, you send that to each connected webSocket.