Angular 12未添加Http标头



我尝试为请求添加验证头:

import {HttpClient, HttpHeaders} from "@angular/common/http";
const httpOptions = {
headers: new HttpHeaders({
'Authorization': `Bearer ${this.user.token}`
})
};
return this.http.post(`http://localhost:8080/api/exchange/producers`, request, httpOptions);

但是头信息没有被添加到请求中。哪里出错了?

您是否尝试过直接设置对象?:

const headers = new HttpHeaders()
.set('Authorization', `Bearer ${this.user.token}`);
return this.http.post(`http://localhost:8080/api/exchange/producers`, request, { headers });

另外,如果需要在多个请求中注入此头,可以使用HTTP_INTERCEPTOR来避免复制和粘贴代码。