从API响应中读取响应头 - Angular 5 + TypeScript [英] Read response headers from API response - Angular 5 + TypeScript

查看:1720
本文介绍了从API响应中读取响应头 - Angular 5 + TypeScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在触发 HTTP 请求,我从中获得了有效的回复。响应还有一个我希望阅读的标题 X-Token 。我正在尝试下面的代码来读取标题,但是,结果我得到null

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 检查中,显示标题存在。尝试查看 StackOverflow 上的几个相关问题,但没有任何帮助。

The response of the API, when checked in Chrome inspect, shows the header is present. Tried looking at several related questions on StackOverflow but nothing helped.

推荐答案

您是否从服务器端公开了x-token?使用access-control-expose-headers。因为不是所有标题都允许从客户端访问,你需要从服务器端公开它们

have you expose 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

也可以在你的前端使用new HTTP 模块使用{ observe:'获取完整响应回复'} 喜欢

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆