首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何查看x-session的状态?

如何查看x-session的状态?
EN

Stack Overflow用户
提问于 2018-08-07 19:50:10
回答 1查看 972关注 0票数 9

我使用的是angular 6,使用的是rest api,后端是laravel php。没有令牌,如果您已登录,您将获得一个x-session,您可以在邮递员标头中看到它

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

如何从angular检查x-sessionX-Session-Expiry的值?在api endpoind中没有任何与session相关的东西。我需要知道会话是否仍然打开,当会话过期时,我需要注销用户。

当您登录时,可以从angular访问这些x-session值吗?它们是否存储在报头中?

服务

  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 });
  }

但是它不工作,我没有任何用户,有解决方案吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-11 04:22:24

在一周内两次,我打开一个问题的赏金,然后回答它,我能做什么?我不能删除它。

所以我需要更改我的登录函数

  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-session的方法

  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 });
    }
  }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51726105

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档