Angular / LocalStorage:尽管设置/获取localStorage,仍然会在页面刷新时注销

时间:2018-01-03 00:09:50

标签: node.js angular typescript local-storage mean-stack

我一直在研究我的第一个MEAN堆栈应用程序。目前,我可以注册新用户并将其登录。但是,当我这样做(登录或注册)时,我无法刷新主页而没有注销。

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

这是我的登录路线

//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');

  }

我应该注意到,当我在获取它们后调试我的localStorage项目时,它们看起来很好。我已经在各种组件中尝试了上述代码,但一直在注销。

非常感谢任何帮助。有谁知道这里会发生什么?非常感谢。

1 个答案:

答案 0 :(得分:0)

当您在应用中时,您正在检查组件中的this.session.token,该组件仅在该服务的实例中设置。刷新时,该值将不存在,您将不会进行身份验证(因为该服务将重新初始化)。

您应该修改逻辑以在init上检查本地存储是否有效令牌。