我使用的是angular 6,使用的是rest api,后端是laravel php。没有令牌,如果您已登录,您将获得一个x-session,您可以在邮递员标头中看到它
X-Session →1948c514b7e5669c284e85d6f612f9bd491
X-Session-Expiry →2038-08-02T09:19:03+00:00
如何从angular检查x-session
和X-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 });
}
但是它不工作,我没有任何用户,有解决方案吗?
发布于 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 });
}
}
https://stackoverflow.com/questions/51726105
复制相似问题