问题
I have some problem that the html view is not change after render the pug file,after getting the server response.
The code is following
app.set('view engine', 'pug');
app.set("views", require('path').join(__dirname, "views"));
app.post('/login', function(req, res, next) {
console.log(req.body);
checkExistanceOfuser(req.body.username, req.body.password, function(err, flag, data) {
console.log(err);
if (err) {
res.send({
err: 'SOME_DATABASE_ERROR'
})
} else {
if (flag) {
req.session.user = data;
/*res.send({
success: true,
message: 'Login Success'
})*/
res.render('welcome', { name: data.name });
} else {
/*res.send({
success: false,
message: 'Invalid Credentials'
});*/
res.render('login', { error: 'Invalid Credentials' });
}
}
})
But i check in network section from browser.The API response (preview) is fine.
回答1:
when you are calling /login
route it's a post call and probably you are using ajax post call for doing so.
Now when you are calling the /login
route its rendering the pug
file
but its not actually effecting the browser DOM. So what you need to do is this
create a new route like this
app.get('/login-success', function(req, res, next) {
if (req.session && req.session.user) {
res.render('welcome', { name: req.session.user.name });
} else {
res.redirect('/');
}
});
and modify the login function like this
app.post('/login', function(req, res, next) {
console.log(req.body);
checkExistanceOfuser(req.body.username, req.body.password, function(err, flag, data) {
console.log(err);
if (err) {
res.send({
err: 'SOME_DATABASE_ERROR'
})
} else {
if (flag) {
req.session.user = data;
res.send({
success: true,
message: 'Login Success'
});
} else {
res.send({
success: false,
message: 'Invalid Credentials'
});
}
}
})
});
in ajax call use this
function login(){
$.post("http://localhost:8000/login",
{
username:document.getElementById("name").value,
password:document.getElementById("password").value,
},
function(data, status){
if(data.success){
window.location = "http://localhost:8000/login-success"
}
});
}
回答2:
You're rendering views/login
, but you've already specified that the view folder is views
. Just render login
.
来源:https://stackoverflow.com/questions/42857413/view-is-not-change-after-render-pug-file-from-express