-->

How can I get HTTP request headers in Angular 4?

2019-07-28 03:52发布

问题:

In internet, I see only add parameter to HTTP request like below.

  this.headers.append('Content-Type', 'application/json');
  this.headers.append('Accept', 'application/json');
  this.headers.append('Access-Control-Allow-Credentials', 'true');

I cannot find how can I get HTTP request header params in Angular 4.

回答1:

The Headers class also has a get(name: string) method, which returns a string, as well as other helpful methods for inspecting the headers. From the Angular docs:

https://angular.io/api/common/http/HttpHeaders

class HttpHeaders {
  constructor(headers?: string | {...})
  has(name: string): boolean
  get(name: string): string | null
  keys(): string[]
  getAll(name: string): string[] | null
  append(name: string, value: string | string[]): HttpHeaders
  set(name: string, value: string | string[]): HttpHeaders
  delete(name: string, value?: string | string[]): HttpHeaders
}

You could also use your browser's developer tools to inspect the request/response headers.

EDIT: It might be helpful if you specify exactly what it is you need to do. Is there a particular header that you need to inspect?

EDIT2: There's also the deprecated Headers class. Not sure which you're using, but there's a lot of overlap in terms of the methods available so it may not even matter.

https://angular.io/api/http/Headers

class Headers {
  constructor(headers?: Headers | {...})
  static fromResponseHeaderString(headersString: string): Headers
  append(name: string, value: string): void
  delete(name: string): void
  forEach(fn: (values: string[], name: string | undefined, headers: Map<string, string[]>) => void): void
  get(name: string): string | null
  has(name: string): boolean
  keys(): string[]
  set(name: string, value: string | string[]): void
  values(): string[][]
  toJSON(): {...}
  getAll(name: string): string[] | null
  entries()
}