繁体   English   中英

Angular 6 HttpClient GET响应未返回自定义标头

[英]Angular 6 HttpClient GET response not returning the custom headers

我是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。

任何帮助表示赞赏。

您需要使用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数据。

请参阅阅读文档中的完整回复

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM