登录后在快速部分显示用户名

Display username in express partial after login

所以我一直在寻找解决方案,但没有解决我的问题。

所以我有一个主页 ('/')、一个个人资料页面 ('/profile') 和一个 login/register 页面。我在本地、推特和 google 帐户中使用护照。我想要做的是在用户访问网站的任何地方的导航栏中显示用户名和个人资料图片。

这是局部的样子:

partials/_nav.hbs

{{#if isAuthenticated}}
             <div class="dropdown">
                <button type="button" class="btn btn-primary dropdown-toggle dropdown-button"
                 data-toggle="dropdown">
                 <img class="user-avatar" src="{{image}}" alt="{{username}}'s' avatar">{{username}}
                </button>
                    <div class="dropdown-menu">
                        <a class="dropdown-item user-dropdown" href="/profile">My Profile</a>
                        <a class="dropdown-item user-dropdown" href="#">User Settings</a>
                        <a class="dropdown-item user-dropdown" href="/logout">Logout</a>
                    </div>
                </div>
                {{else}}
                <a href="/register" class="account-button text-nowrap">Register/Login
                </a>
        {{/if}}

routes/index.js -- 为了显示用户名和图像,在我的路线页面上我有:

// Login
router.get('/', (req, res, user) => {
  res.render('index', {
    username: req.user.username, // <-- line 10 and if I remove this it goes to line 11
    image: req.user.image,
  });
});

// Profile
router.get('/profile', ensureAuth, (req, res) => {
  res.render('profile', {
    username: req.user.username,
    image: req.user.image,
  });
});

那么现在来解决我的问题。主页和个人资料路由实际工作并显示用户名和图像。问题是当我尝试注销时,当我尝试注销时出现此错误:

TypeError: Cannot read property 'username' of undefined
    at C:\Users\Desktop\Code\site\routes\index.js:10:20 // look in code above for this line

我试图通过传递 req.user 对象然后在我的局部中执行 user.username 来解决这个问题。

我有点新手,但我认为问题可能是当我注销时,用户名不再存在,这就是它给出错误的原因。但是,如果是这种情况,它应该显示我的部分中的 login/register 按钮。

请注意,我在 server.js 中将 isAuthenticated 注册为局部变量,如果您需要,这是我的 ensureAuth 代码:

middleware/auth.js

  module.exports = {
  ensureAuth: function (req, res, next) {
    if (req.isAuthenticated()) {
      return next();
    }
    res.redirect('/login');
  },
};

所以我找到了解决方案。在我的回答中,我传递了 req.user.username 而没有检查它是否确实存在。所以我在 reddit 上提问,有人帮我得出了这个答案:

const { user: { username, image } = {} } = req;

它的作用是解构用户对象和 returns 用户名和图像,或者什么都不解构 ({})。

get 请求看起来像这样:

router.get('/', (req, res) => {
  const { user: { username, image } = {} } = req;
  res.render('index', {
    username,
    image,
  });
});