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

问题描述

所以我一直在寻找解决方案已经有一段时间了,对我的问题没有任何作用。

因此,我有一个主页('/'),一个个人资料页面('/ profile')和一个登录/注册页面。我正在本地,twitter和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,res) => {
  res.render('profile',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来解决此问题。

我有点想表达,但是我认为问题可能是当我注销时,用户名不再存在,这就是为什么会出现错误。但是,在这种情况下,它应该显示我的部分中的“登录/注册”按钮。

请注意,我在server.js中将isAuthenticated注册为本地变量,如果需要,这是我的sureAuth代码

中间件/auth.js

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

解决方法

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

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

这是因为它会破坏用户对象,并返回用户名和图像,或者不返回任何内容({})。

get请求看起来像这样:

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