Angular 6 HttpClient GET 响应未返回自定义 headers
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;
}
在我的回复中 header 我得到了这样的东西 -
在我的响应回调中,我试图获取此令牌信息并将其设置到某个存储空间以作为 header 传递给我未来的请求。但是,我的回复 body 是一份 HTML 文档 - 我正在使用
接收
responseType: 'text' as 'json
所以在我的回调中,我没有获取包含 header 的整个响应,而是将 HTML 文档作为文本获取。
为什么我没有收到 header 的完整回复?
注意:我尝试完全删除 responseType - 但后来我总是得到一个 HttpErrorResponse,即使服务器 returns 是 200。
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'
};
Now HttpClient.get() returns an Observable of typed HttpResponse rather than just the JSON data.
请参阅文档中的 Reading the full response。
我是 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;
}
在我的回复中 header 我得到了这样的东西 -
在我的响应回调中,我试图获取此令牌信息并将其设置到某个存储空间以作为 header 传递给我未来的请求。但是,我的回复 body 是一份 HTML 文档 - 我正在使用
接收responseType: 'text' as 'json
所以在我的回调中,我没有获取包含 header 的整个响应,而是将 HTML 文档作为文本获取。
为什么我没有收到 header 的完整回复?
注意:我尝试完全删除 responseType - 但后来我总是得到一个 HttpErrorResponse,即使服务器 returns 是 200。
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'
};
Now HttpClient.get() returns an Observable of typed HttpResponse rather than just the JSON data.
请参阅文档中的 Reading the full response。