如何在Angular中为httpRequest添加自定义标头

8

我正在尝试通过在headers中传递一些values来进行http get()请求,现在我正在这样替换headers

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import {ICustomer} from 'src/app/models/app-models';

@Injectable({
  providedIn: 'root'
})
export class MyService {
private baseUrl = '....api url....';
public authKey = '....auth_key......';

  constructor(private http: HttpClient) { }

  public async AllCustomers(): Promise<ICustomer[]> {
   const apiUrl = `${this.baseUrl}/customers`;

   return this.http.get<ICustomer[]>(apiUrl ,
    {headers: new HttpHeaders({Authorization: this.authKey})}).toPromise();<=====
  }

}

当我这样替换标题时:

headers: new HttpHeaders({Authorization: this.authKey})

默认头部值(即Content-Type:application/json)将被上述标题替换。

“输入图像描述”src而不是替换标题,我该如何添加自定义标题,我尝试过这样做:

  public async AllCustomers(): Promise<ICustomer[]> {
    const apiUrl = `${this.baseUrl}/courses`;
    const headers = new HttpHeaders();
    headers.append('Authorization', this.authKey);
    headers.append('x-Flatten', 'true');
    headers.append('Content-Type', 'application/json');

    return this.http.get<ICustomer[]>(apiUrl).toPromise();
  }

我的方法有什么问题,我是angular的新手,需要帮助吗?


如果你想发送身份验证令牌,为什么不使用HTTP拦截器? - CruelEngine
4个回答

13

您应该像这样在您的get请求中添加标头。由于HttpHeaders是不可变对象,因此您需要重新分配标头对象。

  public async AllCustomers(): Promise<ICourses[]> {
    const apiUrl = `${this.baseUrl}/courses`;
    let headers = new HttpHeaders();
    headers = headers.append('Authorization', this.authKey);
    headers = headers.append('x-Flatten', 'true');
    headers = headers.append('Content-Type', 'application/json');

    return this.http.get<ICourses[]>(apiUrl, {headers}).toPromise();
  }

我已按照您的要求将 header 添加到了请求中。但是出现了以下错误:ERROR Error: Uncaught (in promise): HttpErrorResponse: {"headers":{"normalizedNames":{},"lazyUpdate":null,"headers":{}},"status":401,"statusText":"Unauthorized","url" - SGR
那么你的授权密钥是错误的。请再次检查您的授权密钥。 - Tony Ngo

1
我认为您忘记在请求中添加头对象。
来自:
return this.http.get<ICourses[]>(apiUrl).toPromise();

return this.http.get<ICourses[]>(apiUrl, { headers }).toPromise();

1
import { HttpHeaders } from '@angular/common/http';
import { HttpClient } from '@angular/common/http';


constructor(private _http: HttpClient) { 

}


public getHeaders(): HttpHeaders {
  const headers = new HttpHeaders({
    'Content-Type':  'application/json',
    'Authorization': `Bearer ${this._auth.token}`
  });
  return headers;
}


public getData() {
  const url     = `https://stackoverflow.com/api/test`;
  const body    = { };
  const options = { headers: this.getHeaders() };
  return this._http.post<any>(url, body, options);
}


0
对于 Angular 15,以下代码有效(感谢 George C.)。
let headers = new HttpHeaders({'customHeader', 'customHeaderValue'});

return this.http.post<any>(BaseUrl + 'api/endpoint', formData, { headers: headers, observe: 'response' })

然而以下代码示例只进行了惰性更新。

let headers = new HttpHeaders();
headers = headers.set('customHeader': 'customHeaderValue');
return this.http.post<any>(BaseUrl + 'api/endpoint', formData, { headers: headers, observe: 'response' })

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接