我有一个登录用户的函数,响应在正文中提供了我在 header 中设置的 token 。
this.headers = new HttpHeaders({'Content-Type': 'application/json'});
loginUser(email, password) {
const body = {email, password};
return this.http.post(`${this.serverUrl}/users/login`, body, {
observe: 'response',
headers: this.headers
})
.pipe(
tap(res => {
if (res.body['token']) {
this.jwtToken = res.body['token'];
this.headers.set('x-auth', this.jwtToken);
this.router.navigate(['/firms/create']);
}
})
);
}
然后,当我尝试使用这些 header 发送注销请求时,我发现“x-auth” header 不存在。但我明明是在loginUser函数里设置的。
这是我的注销功能:
logoutUser() {
return this.http.delete(`${this.serverUrl}/users/me/token`, {
observe: 'response',
headers: this.headers
})
.pipe(
tap(res => {
this.headers.delete('x-auth');
this.removeTokenFromLocalStorage(this.jwtToken);
this.jwtToken = null;
})
);
}
这些是我在 LOGOUT 调用中发送到服务器的 header (请注意,我在那里没有 x-auth,尽管我应该有!)
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, br
Accept-Language:
Connection:keep-alive
Content-Type:application/json
Host: censored
Origin:http://evil.com/
Referer:http://localhost:4200/somendpoint
User-Agent:
旁注:我的后端设置为拦截 req.headers['x-auth'] 并使用它进行登录(在身份验证中间件中)。 任何帮助将不胜感激。
最佳答案
HttpHeaders
是不可变的 - 它不会改变,必须重新分配。
将行更改为:
this.headers = this.headers.set('x-auth', this.jwtToken);
在你的删除函数中:
this.headers = this.headers.delete('x-auth');
它应该可以工作。
关于javascript - 在 Angular 5 中设置 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48505604/