【问题标题】:How can I get HTTP request headers in Angular 4?如何在 Angular 4 中获取 HTTP 请求标头?
【发布时间】:2018-03-01 06:14:41
【问题描述】:

在互联网上,我只看到向 HTTP 请求添加参数,如下所示。

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

我找不到如何在 Angular 4 中获取 HTTP 请求标头参数。

【问题讨论】:

  • 可以看网络调用requestheaders
  • 我对 Angular 还是很陌生。能举个例子吗?
  • 看看这个image
  • 谢谢,但我想将此信息带到我的角度代码中。
  • 请求标头是您在请求中发送的内容,因此如果您使用帖子中提到的上述代码,您应该能够在网络中看到

标签: angular http-headers http-request-parameters


【解决方案1】:

如果这对现在正在寻找这个答案的人有用:

request.headers.forEach(h=> {
console.log(h);
console.log(request.headers.get(h));
})

只要请求是HttpRequest,就会在控制台中打印所有标头名称及其对应的值。

我在我的拦截器中使用它来在我的 Angular 10 应用程序中实现 V4 签名,它正在工作 ATM。

你会得到HttpHeaders {normalizedNames: Map(7), lazyUpdate: null, lazyInit: null, headers: Map(7)} 在开发人员工具中查看request.headerscontent 时,因为它是延迟加载的,但是如果您在运行我上面粘贴的代码后再次查看它,您应该在 headers 属性中看到所有现有的标头及其内容(应该匹配控制台中打印的内容)。

来源:我尝试在控制台中运行 Angular 10 应用程序,同时在 Http 拦截器的拦截方法内的断点处暂停。

【讨论】:

    【解决方案2】:

    Headers 类还有一个 get(name: string) 方法,它返回一个字符串,以及其他检查标题的有用方法。来自 Angular 文档:

    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
    }
    

    您还可以使用浏览器的开发者工具检查请求/响应标头。

    编辑:如果您准确指定您需要做什么,这可能会有所帮助。是否有需要检查的特定标头?

    EDIT2:还有已弃用的 Headers 类。不确定您使用的是哪个,但在可用方法方面有很多重叠,因此它甚至可能无关紧要。

    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()
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-28
      • 1970-01-01
      • 1970-01-01
      • 2018-04-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多