从 API 响应中读取响应标头 - Angular 5 + TypeScript [英] Read response headers from API response - Angular 5 + TypeScript
问题描述
我正在触发一个 HTTP
请求,我从它那里得到了一个有效的响应.响应还有一个我希望阅读的标头 X-Token
.我正在尝试使用下面的代码来读取标题,但是,结果为空
I'm triggering a HTTP
request and I'm getting a valid response from it. The response also has a header X-Token
that I wish to read. I'm trying the below code to read the headers, however, I get null as a result
this.currentlyExecuting.request = this.http.request(reqParams.type, reqParams.url, {
body: reqParams.body,
responseType: 'json',
observe: 'response'
}).subscribe(
(_response: any) => {
// Also tried _response.headers.init();
const header = _response.headers.get('X-Token');
console.log(header);
onComplete(_response.body);
},
_error => {
onComplete({
code: -1,
message: Constants.WEBSERVICE_INTERNET_NOT_CONNNECTED
});
}
);
API
的响应,在 Chrome 检查中检查时,显示标头存在.
The response of the API
, when checked in Chrome inspect, shows the header is present.
推荐答案
您是否使用 access-control-expose-headers
从服务器端公开了 X-Token
?因为不是所有的头都允许从客户端访问,你需要从服务器端暴露它们
Have you exposed the X-Token
from server side using access-control-expose-headers
? because not all headers are allowed to be accessed from the client side, you need to expose them from the server side
同样在您的前端,您可以使用新的 HTTP 模块来使用 {observe: 'response'}
获得完整的响应,例如
Also in your frontend, you can use new HTTP module to get a full response using {observe: 'response'}
like
http
.get<any>('url', {observe: 'response'})
.subscribe(resp => {
console.log(resp.headers.get('X-Token'));
});
这篇关于从 API 响应中读取响应标头 - Angular 5 + TypeScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!