如何以角度将自定义标头添加到httpRequest

Posted

技术标签:

【中文标题】如何以角度将自定义标头添加到httpRequest【英文标题】:how to add custom headers to httpRequest in angular 【发布时间】:2019-11-08 00:57:39 【问题描述】:

我正在尝试通过在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)

默认的 headers 值(即 Content-Type : application/json)将被上面的 headers 替换。

我没有替换标题如何添加custom headers,而是这样尝试:

  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 拦截器? 【参考方案1】:

您应该像这样将标头添加到您的获取请求中。此外,由于 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" 那么你的授权密钥是错误的。再次检查您的身份验证密钥【参考方案2】:

我想你忘了在请求中添加 headers 对象

来自

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

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

【讨论】:

【参考方案3】:
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://***.com/api/test`;
  const body    =  ;
  const options =  headers: this.getHeaders() ;
  return this._http.post<any>(url, body, options);


【讨论】:

以上是关于如何以角度将自定义标头添加到httpRequest的主要内容,如果未能解决你的问题,请参考以下文章

如何将自定义 HTTP 请求标头添加到 Thymeleaf 生成的表单或链接?

如何将自定义响应标头添加到来自 azure blob 的响应?

如何将自定义标头添加到zend Mail Message

如何将自定义标头从 mvc 项目发送到 Web api 项目?

将自定义标头添加到 AFNetworking,我做错了啥?

将自定义标头添加到“请求”