【问题标题】:Angular 6 HttpClient GET response not returning the custom headersAngular 6 HttpClient GET 响应未返回自定义标头
【发布时间】:2019-03-01 10:33:42
【问题描述】:

我是 Angular 6 的新手,并且创建了一个新应用程序来替换我们现有的 Angular 1.x 应用程序。 我正在像这样对服务器进行 GET 调用 -

httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' }),
responseType: 'text' as 'json'
};

return this.http.get(this.domain + '/login', this.httpOptions).pipe(
  map((res: HttpResponse<any>) => {
  let myHeader = res.headers.get('X-CSRF-TOKEN');
  return res;
}

在我的响应标题中,我得到了这样的信息 -

在我的响应回调中,我试图获取此令牌信息并将其设置为某个存储以作为标头传递给我未来的请求。但是,我的响应正文是一个 HTML 文档 - 我正在使用

responseType: 'text' as 'json

所以在我的回调中,我只是将 HTML 文档作为文本获取,而不是获取包含标题的整个响应。

为什么我没有得到包含标题和所有内容的完整响应?

注意:我尝试完全删除 responseType - 但即使服务器返回 200,我也总是得到一个 HttpErrorResponse。

SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse

所以我保留了 responseType。

感谢任何帮助。

【问题讨论】:

    标签: angular angular-httpclient


    【解决方案1】:

    您正在寻找HttpClient{observe: 'response'} 选项:

    httpOptions = {
      headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' }),
      responseType: 'text' as 'json',
      observe: 'response'
    };
    

    现在 HttpClient.get() 返回一个类型化 HttpResponse 的 Observable 而不仅仅是 JSON 数据。

    请参阅文档中的Reading the full response

    【讨论】:

    • 谢谢!就是这样。该链接包含我想要的所有详细信息。我已将问题标记为已回答。然而,虽然我现在得到了完整的回应,但我并没有得到所有的标题。我得到的唯一的是“content-type”、“cache-control”、“last-modified”和“expires”。我还不得不说观察:'response' as 'body' 失败,我得到错误“属性'observe' 的类型不兼容。类型'string' 不可分配给类型'“body”'”。我应该将此作为新问题发布吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-25
    • 2019-12-21
    • 1970-01-01
    相关资源
    最近更新 更多