How to dynamically render/load pages in express?

走远了吗. 提交于 2020-01-31 13:26:27

问题


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.


回答1:


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!



来源:https://stackoverflow.com/questions/13573540/how-to-dynamically-render-load-pages-in-express

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!