【问题标题】:How to check the status of x-session?如何检查 x-session 的状态?
【发布时间】:2019-01-14 12:05:43
【问题描述】:

我使用的是 Angular 6,使用了一个 rest api,后端是 laravel php。没有令牌,如果你登录了,你会得到一个 x-session,你可以在邮递员的 headers 中看到它

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

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

登录时可以从角度访问这些 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 });
  }

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

【问题讨论】:

  • 我解决了这个问题,但是既然有一个开放的赏金,如果你想出一个更好的解决方案,我会接受你的回答并给你赏金,我的意思是它必须是一个开放的赏金授予某人或过期

标签: angular angular6


【解决方案1】:

在 1 周内两次,我为一个问题打开赏金然后我回答它,我该怎么办?删除不了。

原来我需要更改我的登录功能

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

【讨论】:

  • 您不能撤销赏金。如果您选择在某个问题上写下赏金,那么无论如何,该声誉都会消失。
  • @IngoBürk 是的,我一周做了两次,今天我为这个问题开了一个赏金然后现在回答了。上周我为stackoverflow.com/questions/51274669/…开了一个赏金,第二天就回答了。没关系,只要我们得到答案并扩展我们的知识就完全没问题,但我不知道为什么我急于打开赏金而不是花更多时间弄清楚。我不喜欢这样的自己
猜你喜欢
  • 2011-12-19
  • 2018-01-06
  • 2013-08-28
  • 1970-01-01
  • 1970-01-01
  • 2016-04-26
  • 2018-05-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多