首页 文章

Angular 6 - 无法向httpClient添加标头(httpClient - @ angular / common / http)

提问于
浏览
0
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)

2 回答

  • 0

    您需要将 Headers 内容更改为“Bearer”而不是“JWT标记”,并将标记内部传递给它 .

    const authHeaders =  new HttpHeaders();
    authHeaders.append('Content-Type', 'application/json');
    authHeaders.append('Authorization', 'Bearer ' + this.token);
    
    const httpOptions = {
      headers: authHeaders
    };
    
  • 0

    @ angular / common / http / HttpHeaders是不可变的 . 然后您的代码应修改如下 .

    const authHeaders =  new HttpHeaders();
    authHeaders = authHeaders.append("Content-Type", "application/json");
    authHeaders = authHeaders.append("Authorization", "Bearer " + "token");
    

相关问题