代码之家  ›  专栏  ›  技术社区  ›  Lynob

如何检查x会话的状态?

  •  10
  • Lynob  · 技术社区  · 6 年前

    我使用的是angular 6,使用的是rest api,后端是laravel php。没有标记,如果您登录,您将得到一个x会话,您可以在postman头中看到它

    X-Session →1948c514b7e5669c284e85d6f612f9bd491
    X-Session-Expiry →2038-08-02T09:19:03+00:00
    

    如何检查 x-session X-Session-Expiry 从角度看?api端点中没有与会话相关的内容。我需要知道会话是否仍处于打开状态,当会话过期时,我需要注销用户。

    当您登录时,可以从角度访问这些x会话值吗?它们存储在标题中吗?

    服务

      login(username, password) {
        const data = {
          username: username,
          password: password
        };
        const headers = new HttpHeaders();
        headers.set('Content-Type', 'application/json');
        localStorage.setItem('headers', JSON.stringify(headers));
        return this.http.post(this.login_url, data, { headers: headers });
      }
    

    我试着给用户服务提供相同的会话

      getUsers() {
        const headers = JSON.parse(localStorage.getItem('headers'));
        return this.http.get(this.users_url, { headers: headers });
      }
    

    但它不起作用,我没有任何用户,有解决办法吗?

    1 回复  |  直到 6 年前
        1
  •  0
  •   Lynob    6 年前

    一周内两次,我对一个问题开出悬赏状然后回答,我能做什么?我不能删除它。

    所以我需要更改我的登录功能

      login(username, password) {
        const data = {
          username: username,
          password: password
        };
        const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
        return this.http.post(this.login_url, data, { headers: headers, observe: 'response' });
      }
    

    这就是你如何得到x-会话

      onLogin() {
        this.auth.login(this.username, this.password).subscribe(data => {
          this.auth.setLoggedIn(true);
          localStorage.setItem('login', JSON.stringify(this.auth.isLoggedIn));
          if (localStorage.getItem('data') === null) {
            localStorage.setItem('data', JSON.stringify(data));
          }
          const session = data.headers.get('x-session');
          const expiry = data.headers.get('x-session-expiry');
          localStorage.setItem('session', JSON.stringify(session));
          localStorage.setItem('session-expiry', JSON.stringify(expiry));
    
    
          this.router.navigate(['']);
        }, err => {
          console.log(err);
        });
      }
    

    这就是你使用它的方式,例如 getUsers 从上面

      getUsers() {
        const session = JSON.parse(localStorage.getItem('session'));
        if (session != null) {
          let headers = new HttpHeaders().set('Content-Type', 'application/json');
          headers = headers.set('x-session', session);
          return this.http.get(this.users_url, { headers: headers });
        }
      }
    
    推荐文章