HittmanA
HittmanA

Reputation: 179

How to live update a JSON response (Express NodeJS)

Basically what I want to do is use express to return a JSON object when a user visits / . I know how to send something like Hello World or even an entire file, but I don't know how to send just a JSON object (e.g. {"foo":1}) in such a way that I can update the data on the client side. For example. Say I have express send the above JSON ({"foo":1}) when a user visits / . How can I then change the value of foo (e.g. increment it, say, every second) and return that without the client having to reload their page?

Upvotes: 2

Views: 6587

Answers (2)

ippi
ippi

Reputation: 10167

So, let's say you have something like this on your express backend:

var obj = {foo: 1};
setInterval(
  function(){ obj.foo++; }),
  1000
);

app.route('/').get(function(req, res, next) {
  res.json(obj);
});

And assuming you are pulling in the data using ajax. (using jQuery since pure javascript ajax can get lengthy.)

<script>
    var foo = 0;
    $.get( "http://backend:3000/", function( data ) {
        foo = data.foo;
    });
</script>

If you want to keep foo updated, you can either do "long polling" (keep requesting the data every few seconds and update it):

function updateFoo(){
    $.get( "http://backend:3000/", function( data ) {
        foo = data.foo;

        // Expect each request to take some time as well...            
        setTimeout( updateFoo, 1000); 
    });
}
updateFoo(); // Call once to start polling.

We used to do it this way because there was no way for the server to initiate a request to the client. So every time you want an update you have to ask for it. It gets messy doing it this way as your app grows and with many users the server will get annoyed as well. (Quit poking me!)

But nowadays we have websockets. And with node.js socket.io is really a nice fit. As for your comment about sending an entire page, I'm guessing you are refering to the socket.io get-started-example:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

// I assume you are refering to this? 
// It's only purpouse is to serves the front-end to the user. 
// If you are serving your app using Apache or perhaps Nginx, then you can remove it.
app.get('/', function(req, res){
  res.sendfile('index.html');
});

io.on('connection', function(socket){
  console.log('a user connected');
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});

If you separate front and backend, then you also need to point your client-script to your socket-io backend:

<script>
  // As opposed to just "io();" when express is serving both front and back:
  var socket = io('http://backend:3000');  

  socket.on('foo', function (data) {
    console.log(data);
  });
</script>

Upvotes: 2

Chaitanya Sama
Chaitanya Sama

Reputation: 330

You can find some good info with examples here for what you need.

http://hungtran.co/long-polling-and-websockets-on-nodejs/

Upvotes: 0

Related Questions