在我的Node.JS Express应用程序中更新用户(通过数据库更新)时,我更新了一个用户会话,然后更新res.locals.session
但是,当我尝试访问Jade模板中的res.locals.session时,这些值将显示为数据库更新之前的值。
请您帮我解一下为什么res.locals.session没有在模板中更新?
这是我的代码(为简洁而减少):
index.js
// Store session to locals so I can use it in Jade
app.use(function (req, res, next) {
res.locals.session = req.session;
next();
});
路由/ user.js的
var User = require('../models/Users');
function displaySettings(req, res) {
res.render('settings');
}
function saveSettings(User, req, res) {
// Updating user
User.update(
{ Member_id: req.session.user.Member_id }
, { settings: req.body }
, { upsert: false, multi: false }
, function (err) {
//if(err) return next(err);
//res.json({ message : 'Success!'});
console.log("saved");
});
// Retrieving user again, so that I can resave the updated user's details
// in the res.locals.session
var user = User.findById(req.session.user._id, function (err, user) {
console.log("found");
console.log(user);
req.session.user = user;
console.log(req.session.user);
res.locals.session = req.session;
console.log(res.locals.session);
});
// Finally display the view
displaySettings(req, res);
}
视图/ settings.jade
extends layout
block content
include includes/navigation
div.container.main
h1.text-center User Settings
div.row
div.col-md-6.col-md-offset-3
form#form-login.form-horizontal(action='/settings',method='post')
div#container(data-role='fieldcontain')
fieldset(data-role='controlgroup')
div.form-group
label.col-sm-4.control-label(for='username') Paypal Email
div.col-sm-8
// The session.user.settings.paypalEmail is showing
// the old value even after the user has re-saved
// their settings. I'm expecting the new, updated
// value to be displayed instead
input.form-control(id='username',type='text',value='#{session.user.settings.paypalEmail}',name='paypalEmail')
答案 0 :(得分:0)
尝试使用res.redirect('settings')
而不是调用displaySettings(req, res)
。我认为这将允许res.locals
更新。
答案 1 :(得分:0)
如何重写saveSettings
如下。
function saveSettings(User, req, res) {
// Updating user
User.update(
{ Member_id: req.session.user.Member_id }
, { settings: req.body }
, { upsert: false, multi: false }
, function (err) {
//if(err) return next(err);
//res.json({ message : 'Success!'});
console.log("saved");
// Retrieving user again, so that I can resave the updated user's details
// in the res.locals.session
var user = User.findById(req.session.user._id, function (err, user) {
console.log("found");
console.log(user);
req.session.user = user;
console.log(req.session.user);
res.locals.session = req.session;
console.log(res.locals.session);
// Finally display the view
displaySettings(req, res);
});
});
}