rettetdemdativ
rettetdemdativ

Reputation: 379

NodeJS update post list

I'm working on a home page that displays text posts as part of a bigger project. When the user sends a GET request for / the home page is returned via

res.render('home', {
    user: req.ping_session, 
    posts: p_l
});

p_l is an array returned by my mongoDB database.

The problem is, that I'm trying to update the list of posts without reloading the page and I don't know how to update 'posts' without saving it as a global variable somewhere via JS. Is there any way to update only the list of posts? I also thought about doing that via sockets, but I don't think it's really necessary here.

I'd really appreciate some help from you guys since I'm quite new to Node.

Thanks in advance! :)

code can be found here: https://github.com/mkocs/ping/tree/testing https://github.com/mkocs/ping/blob/testing/routes/routes.js <-- my routes file which returns the page https://github.com/mkocs/ping/blob/testing/views/home.jade <-- the page that's returned

Upvotes: 0

Views: 171

Answers (1)

jtmarmon
jtmarmon

Reputation: 6179

There's no way to reload posts without reloading the page in your current state.

The way your application works currently is that it receives an HTTP request, processes it and then spits out (renders) some data to the browser. Then that connection is terminated. After you've rendered the page, you have no way of communicating with the browser unless they open a new request with you, in which case you would have no way of associating the first request with the second (except for IP address which is not something you should rely on).

You may wish to look into websockets (I recommend socket.io for node) which is a different type of connection than a regular HTTP request where the browser and the server maintain a connection and pass messages back and forth, rather than a single request-response.

Many sites use websockets for things like this. Often times they'll use a mix. For example, when you're on Stack Overflow, you make a web request which renders the page you're looking at, but SO also maintains a websocket for little events like 'hey the user has a new notification in their inbox'. In your case, you could trigger an event that tells the client, 'hey, your user has a new post waiting for him/her'. Once you receive that, you could load the next post using AJAX (a method of creating regular HTTP requests from the browser).

Hope this gives you some direction.

Upvotes: 1

Related Questions