简体   繁体   English

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

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

I am new to Angular 6 and have created a new application to replace our existing Angular 1.x application. 我是Angular 6的新手,并创建了一个新应用程序来替换我们现有的Angular 1.x应用程序。 I am making a GET call to the server like so - 我正在像这样对服务器进行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;
}

In my response header I get something like this - 在我的响应标头中,我得到这样的信息-

在此处输入图片说明

In my response callback I am trying to get this token info and set it to some storage to pass as header to my future request. 在我的响应回调中,我试图获取此令牌信息并将其设置为一些存储,以作为标头传递给我的未来请求。 However, my response body is an HTML document - which I am receiving using 但是,我的响应主体是一个HTML文档-我正在使用它接收

responseType: 'text' as 'json

So inside my callback, instead of getting the entire response which includes the headers, I am just getting the HTML document as text. 因此,在我的回调内部,而不是获取包含标头的整个响应,而是将HTML文档作为文本获取。 在此处输入图片说明

Why am I not getting the complete response with header and all? 为什么我没有得到标头和全部的完整响应?

Note: I tried removing the responseType altogether - but then I'm always just getting an HttpErrorResponse even though the server returns a 200. 注意:我尝试完全删除responseType,但是即使服务器返回200,我总是总是得到HttpErrorResponse。

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

So I have retained the responseType. 所以我保留了responseType。

Any help is appreciated. 任何帮助表示赞赏。

You're after the {observe: 'response'} option for HttpClient : 您需要使用HttpClient{observe: 'response'}选项:

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

Now HttpClient.get() returns an Observable of typed HttpResponse rather than just the JSON data. 现在,HttpClient.get()返回一个类型为HttpResponse的Observable,而不仅仅是JSON数据。

See Reading the full response in the docs. 请参阅阅读文档中的完整回复

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

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