我正在尝试检索当前用户会话,然后将数据发送到视图,但在视图中没有任何显示i事件检查数据库,并且存在包含所有信息的活动会话。我尝试将用户登出并重新开始。这是我的代码。
登录效果很好
router.post('/', jsonParser, function (req, res) {
if (!req.body || req.body.length === 0) {
console.log('request body not found');
return res.sendStatus(400);
}
var username = req.body.username;
var password = req.body.password;
Parse.User.logIn(username, password, {
success: function (user) {
res.redirect('/');
console.log(JSON.stringify(user));
},
error: function (user, error) {
}
});
});
在index.js
中检索当前用户var username;
/* GET home page. */
router.get('/', function (req, res, next) {
var currentUser = Parse.User.current();
if (currentUser){
currentUser.fetch().then(function (fetchedUser) {
this.username = fetchedUser.getUsername();
}, function (error) {
console.log(error.message);
});
}
res.render('index', {title: 'Home', user: this.username});
});
module.exports = router;
当我尝试显示用户名h1=user
时,没有显示任何内容。
答案 0 :(得分:1)
您可以使用箭头功能访问外部上下文(this
):
currentUser.fetch().then(fetchedUser => {
this.username = fetchedUser.getUsername();
}, error => console.error(error));
但是,它无法帮助您,因为您尝试在提取用户之前呈现。你需要等待fetch完成。
if (currentUser) {
currentUser.fetch().then(function(fetchedUser) {
res.render('index', {title: 'Home', user: fetchedUser.getUsername()});
}).catch(function(err) {
console.error(err);
// may be render something with err.message here
});
} else {
// render without user
res.render('index', {title: 'Home', user: null});
}
答案 1 :(得分:0)
不确定您是否获得了this.username
/* GET home page. */
router.get('/', function (req, res, next) {
var currentUser = Parse.User.current();
var that = this;
if (currentUser){
currentUser.fetch().then(function (fetchedUser) {
that.username = fetchedUser.getUsername();
}, function (error) {
console.log(error.message);
});
}
res.render('index', {title: 'Home', user: that.username});
});
module.exports = router;
存储this
的引用,然后尝试使用res.render