使用HttpClient-Angular时如何捕获所有标头

问题描述 投票:0回答:1

使用JavaScript XMLHttpRequest,我可以轻松地使用getAllResponseHeaders()方法获取标头

var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
var headers = req.getAllResponseHeaders().toLowerCase();

获得与此类似的结果:

accept-ranges: bytes
access-control-allow-origin: *
content-length: 4546
content-type: text/html; charset=UTF-8
date: Mon, 18 May 2020 04:24:30 GMT
etag: W/"11c2-u8XhnlVk5uwUwaHTXsnarcbbBQw"
x-powered-by: Express

现在我想在Angular中使用它,但是当我使用HttpClient启动请求时,我不知道如何获取这些值。

javascript angular xmlhttprequest httpclient
1个回答
0
投票

您可以以角度使用http-interceptor。拦截器是对每个HTTP请求或响应执行某些工作的方式。

这里您可以同时获得请求和HTTP请求的标头

例如,请检查以下链接:

https://blog.angulartraining.com/http-interceptors-in-angular-61dcf80b6bdd

在拦截器的以下部分(响应后)

return next.handle(authReq).pipe(
  // We use the map operator to change the data from the response
  map(resp => {
     // Several HTTP events go through that Observable 
     // so we make sure that this is a HTTP response
     if (resp instanceof HttpResponse) {
        //extract your headers here
       let newHeaders = resp.headers;
    }
  })
);
© www.soinside.com 2019 - 2024. All rights reserved.