Angular/LocalStorage:尽管设置/获取了localStorage,但刷新页面时仍保持注销状态 [英] Angular/LocalStorage: Keep getting logged out on page refresh, despite setting/getting localStorage

查看:243
本文介绍了Angular/LocalStorage:尽管设置/获取了localStorage,但刷新页面时仍保持注销状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在研究我的第一个MEAN堆栈应用程序.目前,我可以注册新用户并登录.但是,无论是我(登录还是注册),我都无法在不注销的情况下刷新主页.

I've been working on my first MEAN stack application. Currently, I am able to sign up new users and log them in. However, when I do either (login or sign up), I am unable to refresh the home page without getting logged out.

我已经成功设置了localStorage,并且可以在父组件中获取它,但是问题仍然存在.我一直在寻找很多S.O.问题,但似乎无法确定.

I have successfully setting my localStorage, and can get it in my parent component, but the issue remains. I've been looking through lots of S.O. questions, but can't seem to nail it down.

这是我的登录帖子路线

//LOGIN POST
router.post('/login', (req, res) => {
  let email;
  let password;

  if(req.body.email && req.body.password) {
    email = req.body.email;
    password = req.body.password;
  }

  if (email === "" || password === "") {
    res.status(401).json({message: "Please provide both email and password"});
    return;
  }

  //Find the user in database.
  User.findOne({ "email": email }, (err, user) => {
    if ( !user ){
      res.status(401).json({message: "Email doesn't exist!"});
    } else {
      bcrypt.compare(password, user.password, function(err, isMatch) {
        if (!isMatch) {
          return res.status(401).json({message: "Password doesn't match.  Please try again..."});
        } else {

          req.session.user = user;  //Storing user data in the session

          var payload = {id: user._id};
          var token = jwt.sign(payload, jwtOptions.secretOrKey, { expiresIn: "24h" });
          return res.json({ message: "ok", token: token, user: user });
          // res.status(200).json({message: "Welcome back...", token: token, user: user});


        }
      });
    }
  });
});

这是我在authService中的登录方法

public token: string;
isAuth: EventEmitter<any> = new EventEmitter();

login(user) {
  return this.http.post(`${this.BASE_URL}/login`, user)
    .map((response) => {
      console.log("here's the response", response);
      console.log("here's the token", response.json());
      let token = response.json() && response.json().token;
      // let currentUser = response.json().user;
      let currentUser = JSON.stringify(response.json().user);

      if(token) {
        console.log("here's the token", token);
        //set token property
        this.token = token;

        this.isAuth.emit(true);

        //store username and jwt in local storage to keep user logged in between page refreshes
        localStorage.setItem('token', token);
        localStorage.setItem('user', currentUser);


        return true; //return true to indicate successful login
      } else {
        return false;
    }
    })
    .catch((err) => {
      return Observable.throw(err);
    });
}

这是我在类别"组件(父组件)中正在做的事情

isAuth: boolean;
  user: any;
  token: any;

  constructor(
    private session: AuthService,
    private router: Router
  ) {
    //checks isAuth event emitter in login to see if it's true.  If it is, subscribe the result to our local isAuth variable
    this.session.isAuth
      .subscribe((isAuth: boolean) => this.isAuth = isAuth );

    //if token exists, authenticated
    if (this.session.token) {
      this.isAuth = true;
      localStorage.getItem('token');
      localStorage.getItem('user');
    //if not, not authenticated
    } else {
      this.isAuth = false;
    }


  }



  ngOnInit() {

    localStorage.getItem('token');
    localStorage.getItem('user');

  }

我应该注意,当我在获取本地存储项的console.log时,它们看起来很好.我已经在各种组件中尝试了上面的代码,但是不断注销.

I should note that when I console.log my localStorage items after getting them, they appear just fine. I've tried the above code in various components, but keep getting logged out.

我们非常感谢您的帮助.有人知道这里会发生什么吗?非常感谢.

Any help is much appreciated. Does anyone know what might be happening here? Thanks a lot.

推荐答案

您正在检查组件中的this.session.token,该组件仅在您位于应用程序中时在该服务的实例中设置.刷新时,该值将不存在,也不会通过身份验证(因为该服务将被重新初始化).

You’re checking this.session.token in the component which is only set in the instance of that service while you’re in the app. When you refresh that value won’t exist and you won’t be authenticated (because the service will be reinitialized).

您应该重新设计逻辑,以便在本地检查init上的有效令牌.

You should rework the logic to check local storage for a valid token on init.

这篇关于Angular/LocalStorage:尽管设置/获取了localStorage,但刷新页面时仍保持注销状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆