Javascript 设置角5中的标题
我有一个登录用户的函数,响应在主体中给我一个标记,我在标题中设置了这个标记Javascript 设置角5中的标题,javascript,node.js,angular,angular5,Javascript,Node.js,Angular,Angular5,我有一个登录用户的函数,响应在主体中给我一个标记,我在标题中设置了这个标记 this.headers = new HttpHeaders({'Content-Type': 'application/json'}); loginUser(email, password) { const body = {email, password}; return this.http.post(`${this.serverUrl}/users/login`, body, {
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']);
}
})
);
}
然后,当我尝试使用这些头发送注销请求时,我发现“x-auth”头不存在。但我在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;
})
);
}
this.headers = this.headers.delete('x-auth');
这些是我在注销呼叫时发送到服务器的头文件(注意我那里没有x-auth,尽管我应该!)
旁注:我的后端被设置为截取req.headers['x-auth'],并使用它登录(在auth中间件中)。
任何帮助都将不胜感激。
HttpHeaders
是不可变的-它不会更改,必须重新分配
将行更改为:
this.headers = this.headers.set('x-auth', this.jwtToken);
在删除功能中:
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;
})
);
}
this.headers = this.headers.delete('x-auth');
它应该可以工作。HttpHeaders是不可变的-它不会更改,必须重新分配 将行更改为:
this.headers = this.headers.set('x-auth', this.jwtToken);
在删除功能中:
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;
})
);
}
this.headers = this.headers.delete('x-auth');
它应该会起作用。可能的重复解决了它的可能重复!谢谢我以前写过应用程序,我过去只设置头,但我没有想到HttpHeaders是不可变的。再次感谢,这就解决了!谢谢我以前写过应用程序,我过去只设置头,但我没有想到HttpHeaders是不可变的。再次感谢。