Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically render/load pages in express?

I need to dynamically load/render part of a page in nodejs (v1.8.15) with express (>3.0) framework. Generally, I want to create a single-page app.

I have a menu at the top of the page with links. Clicking on the links will change the content below, as in AJAX page loading.

For example:

>home|login|signup|chat
..content for home..

If I press the 'signup' link:

home|login|>signup|chat
..content for signup..

In express I have routes on the server:

var express = require('express');
var app = express();

app.get('/signup', function(req, res) {
    // render signup.jade
    res.render('signup');
}
app.post('/signup', function(req, res) {
    // .. work with information
    if (ok) res.send('ok', 200); else res.send(error, 200);
}

After reading this, I figured out that I should use socket.io. I know sockets well, so it will be easy to send data about 'clicking on link' from the client to the server.

Q1: How do I render/load pages dynamically like I wrote in express?

Yes, I could use AJAX for page loading, but will it work for .post methods in express? How should I organize my thoughts to create such a site?

By the way, I've read about Derby and SocketStream, but I didn't understand.

Q2: Can I use Derby or SocketStream in my aims (site functions: login, signup, chat)? How?

If SocketStream is what I need, that would be very bad, because Heroku doesn't work with it.

like image 981
sirjay Avatar asked Dec 26 '22 14:12

sirjay


1 Answers

Q1) This is in fact very simple, no need for Socket.io, Derby or whatever. You can call any expess route with any method through ajax, using jQuery makes ajax very easy. In your example, let's suppose your container HTML file has a div with id 'container', which is where you want the ajax-loaded content to go:

$.ajax({ url: 'http://yoursite.com/signup'
     , type: 'GET'
     , dataType: 'html'
    })
.done(function(data) {
  $('#container').html(data);
})
.fail(function() {
  console.log("Something went wrong!");
});

Express supports all HTTP verbs (GET, POST, PUT etc.). For loading pages dynamically, use GET, then when a user enters some login information you can POST it to an Express route that will tell you if it is valid or not, and you use jQuery to modify the DOM accordingly.

Q2) As said in Q1, no need to use Derby or SocketStream. Plain old jQuery + basic Express will get you where you want!

like image 124
Louis Chatriot Avatar answered Dec 31 '22 09:12

Louis Chatriot