Nodejs / express和ejs:渲染

时间:2016-06-30 02:58:58

标签: javascript node.js express ejs

抱歉,我不会说英语。

我会尝试

当LOGIN = OK => welcome.ejs => hello user_id< =它的成功!

当LOGIN = X => welcome.ejs =>登录链接< =失败。错误

错误信息是:无法读取属性' id'未定义的

我不知道为什么不这样做。 我该如何解决这个问题?

welcome.ejs

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>welcome</title>
</head>
<body>
<h1>welcome</h1>
<% if (user.id) { %>
<p><%= user.id %> hello!</p>
<% } else { %>
<p><a href="/login">LOGIN</a></p>
<% } %>
</body>
</html>

index.js

router.get('/login', function(req, res, next) {
  res.render('login');
});

passport.serializeUser(function(user, done) {
  done(null, user.id);
});

passport.deserializeUser(function(id, done) {
  var uid = id;
  pool.getConnection(function(err, connection) {
    connection.query('select * from member where id=?', [uid], function(err, rows) {
        connection.release();
        var user = rows[0];
        if(user.id === id) {
            done(err, user);
        }
    });
  });
});

passport.use(new LocalStrategy(
  function(username, password, done) {
    var uid = username,
            upw = password;
    pool.getConnection(function(err, connection) {
        connection.query('select * from member where id=?', [uid], function(err, rows) {
            connection.release();
            var user = rows[0];
            if(uid === user.id && upw === user.pass) {
                console.log('LocalStrategy', user);
                return done(null, user);
            } else {
                return done(null, false);
            }
        });
      });
    }
));

router.post('/login',
  passport.authenticate('local', { successRedirect: '/welcome',
                               failureRedirect: '/login',
                               failureFlash: false })
);

// here is problem
router.get('/welcome', function(req, res, next) {
  console.log('welcome user', req.user);
  console.log('welcome user.id : ', req.user.id);

  var obj = {user: req.user};
  res.render('welcome', obj);
});

1 个答案:

答案 0 :(得分:0)

将欢迎文件更改为:

<% if (user) { %>

而不是

<% if (user.id) { %>