无法从req.user获取用户名,以便在快递中输出

时间:2017-02-02 03:34:50

标签: javascript express ejs

我正在使用ejs尝试从节点快速应用程序中的req.user输出用户名,但它似乎无法正常工作。

这是我的用户名和密码的来源:

app.get('/', function(req, res) {
    res.render('index', {
        isAuthenticated: req.isAuthenticated(),
        user: req.user
    }); 
    console.log("req.user:", req.user);
});

此时,我可以看到终端中的req.user显示如下:

req.user: [ { _id: 5890f8a97ef995525d4b78cd,
    username: 'dave',
    password: 'somepassword',
    __v: 0 } ]

这就是我在index.ejs中所拥有的:

<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<head>
<body>
  <% if (!isAuthenticated) { %>
    <a href="/login">Log in here</a>
  <% } else { %>
    Hello, <%= user.username %>!
    <a href="/logout">Log out</a>
  <% } %>
</body>
</html>

这是登录表单:

<!DOCTYPE html>
<html>
<head>
<title>Passport</title>
<head>
<body>
<form action="" method="post">
    <input type="text" name="username" placeholder="Username">
    <input type="password" name="password" placeholder="Password">
    <input type="submit" value="Login">
</form>
</body>
</html>

我最初在我的index.ejs中有这个,但仍然没有输出用户名。

Hello, <%= user.name %>!

感谢任何帮助。

1 个答案:

答案 0 :(得分:4)

根据终端显示的内容,req.user似乎是一个包含对象的数组,这意味着在访问对象的属性之前,您需要访问数组中的一个元素。 / p>

因此<%= user.username %>将是<%= user[0].username %>

<% if (!isAuthenticated) { %>
  <a href="/login">Log in here</a>
<% } else { %>
  Hello, <%= user[0].username %>!
  <a href="/logout">Log out</a>
<% } %>

或者您可以更新Web服务以传递user数组中的第一个元素:

res.render('index', {
  isAuthenticated: req.isAuthenticated(),
  user: req.user[0]
}); 
<% if (!isAuthenticated) { %>
  <a href="/login">Log in here</a>
<% } else { %>
  Hello, <%= user.username %>!
  <a href="/logout">Log out</a>
<% } %>

您可能还想检查user数组是否包含任何元素,以防止在没有错误的情况下抛出任何错误:

res.render('index', {
  isAuthenticated: req.isAuthenticated(),
  user: (req.user && req.user.length) ? req.user[0] : {}
});