问题
I'm using node and express with the mustache templating system, I have created a multipage website but don't want it refresh on rendering (make it single page), what can i do to solve this?
i think i need to use ajax, i'm just not sure how.
right now it is rendering the url on to another page, but i need it to render on the same page.
this is some of the code
const express = require('express');
const parseurl = require('parseurl');
const bodyParser = require('body-Parser');
const path = require('path');
const expressValidator = require('express-validator');
const mustacheExpress = require('mustache-express');
const models = require('./models');
const session = require('express-session');
const app = express();
app.engine('mustache', mustacheExpress());
app.set('view engine', 'mustache');
app.set('views', './views')
app.use(express.static('public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(expressValidator());
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true
}));
app.get('/', function(req, res) {
res.render('index')
})
app.get('/signup', function(req, res) {
res.render('signup');
});
app.get('/login', function(req, res) {
res.render('login');
});
app.get('/login', function(req, res) {
if (req.session && req.session.authenticated) {
var user = models.user.findOne({
where: {
username: req.session.username,
password: req.session.password
}
}).then(function(user) {
if (user) {
req.session.username = req.body.username;
req.session.userId = user.dataValues.id;
let username = req.session.username;
let userid = req.session.userId;
res.render('index', {
user: user
});
}
})
} else {
res.redirect('/home')
}
})
app.post('/login', function(req, res) {
let username = req.body.username;
let password = req.body.password;
回答1:
If you are trying to convert your app to use a single page architecture, while still pre rendering all of your HTML on the server, you will need to implement some form of a client side router like this one. In your client-side code, within the callback for each route, you can make an AJAX call to your server, and then replace the entire html document with the html the server returns. Something like this if you are using jquery:
route('/login', function(name) {
$.get("/login", {
anyotherparamsyouwanttosend: "whatever",
},
function(htmlResponse) {
$('html').html(htmlResponse);
})
})
But there's not much of an advantage to this approach over a traditional multi-page architecture. A better approach would be to render the mustache templates on the client side. In your Express code you would use res.json
instead of res.render
to send just the data you need to render the Mustache template on the client side instead of sending a big block of HTML.
Hope this helps!
来源:https://stackoverflow.com/questions/55269102/dynamically-loading-webpage-using-node-express-need-to-render-on-the-same-page