【问题标题】:how to add custom headers to httpRequest in angular如何以角度将自定义标头添加到httpRequest
【发布时间】: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 拦截器?

标签: javascript node.js angular typescript rxjs


【解决方案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://stackoverflow.com/api/test`;
      const body    = { };
      const options = { headers: this.getHeaders() };
      return this._http.post<any>(url, body, options);
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-18
      • 1970-01-01
      • 2012-04-23
      • 2012-04-02
      • 2019-08-17
      • 1970-01-01
      • 2017-02-15
      相关资源
      最近更新 更多