const httpOptions = {
headers: new HttpHeaders({
"Content-Type" : "application/json",
"Authorization": "JWT Token"
})
};
// http通话
return this.http.get(apiUrl, httpOptions).pipe(
map(this.extractData),
catchError(this.handleError));
此请求有效,但标头未传递到服务器。似乎无法使用@ angular / common / http
传递标题const authHeaders = new HttpHeaders();
authHeaders.append("Content-Type", "application/json");
authHeaders.append("Authorization", "Bearer " + "token");
const tt = authHeaders.get("Content-Type");
const pp = authHeaders.get("Authorization");
当我使用get读取标题时,它返回null。似乎HttpHeaders类有一些问题(@ angular / common / http)
答案 0 :(得分:0)
您需要将标头内容更改为“ Bearer”而不是“ JWT令牌”,并将令牌传递到其中。
const authHeaders = new HttpHeaders();
authHeaders.append('Content-Type', 'application/json');
authHeaders.append('Authorization', 'Bearer ' + this.token);
const httpOptions = {
headers: authHeaders
};
答案 1 :(得分:0)
@ angular / common / http / HttpHeaders是不可变的。然后,您的代码应进行如下修改。
const authHeaders = new HttpHeaders();
authHeaders = authHeaders.append("Content-Type", "application/json");
authHeaders = authHeaders.append("Authorization", "Bearer " + "token");
答案 2 :(得分:0)
获取令牌:
let token = localStorage.getItem('token');
开始为您正在使用的服务器提供服务。在所有HTTP方法中,都有另一个参数是一个对象,并且在该对象中有一个名为标题的键。那么此键的值是另一个对象,键:此对象的值是您请求的值和标头。
http.get('someurl',{
headers: {'header1':'value1','header2':'value2'}
});
在实际示例中,可能是这样的:
getOrders(){
let token = localStorage.getItem('token');
return this.http.get('/api/orders' , {headers:
{'Authorization':'Bearer ' + token}});
}
通过此实现,您可以将令牌标头粘贴到您的请求中。
答案 3 :(得分:0)
只需尝试一下
let headers: HttpHeaders = new HttpHeaders();
headers = headers.append('Content-Type', 'application/json');
headers = headers.append('Authorization', '12345');
const tt = headers.get("Content-Type");
const pp = headers.get("Authorization");