从Angular中的HttpClient post请求获取响应头?

时间:2017-08-17 16:01:19

标签: angular http-headers httpresponse angular-http angular-httpclient

我正在尝试从post请求中获取响应头,但是HttpResponse对象不包含我在网络中可以看到的相同头。我究竟做错了什么?我需要访问Apiproxy-Session-Id键的值,它不存在于HttpHeaders中。

这是执行post请求并记录完整响应的代码,其中http是HttpClient对象。

this.http.post('http://localhost:8081/user/login', JSON.stringify(requestBody), {observe: 'response'}).subscribe(resp => { console.log(resp); });

This is the response I'm logging.

These are the headers I'm seeing in the network.

我是Angular的新手并且非常难过。谢谢你的帮助!

2 个答案:

答案 0 :(得分:4)

嘿,我在这里遇到同样的问题。由于您的后端和前端位于不同的域上,因此默认情况下不会公开响应的某些标头。

您可以尝试两种不同的方法:

<强> 1。在Angular上代理您的请求

使用此代理将使您的后端认为该请求来自sabe域。请参阅this doc以了解如何操作。请注意,使用此选项将显示所有标题

<强> 2。在后端服务器上公开所需的标题

由于我不知道你后端的语言,我不能一步一步地告诉你 这样做,但是我必须做类似的事情。这个回复:response.add("Access-Control-Expose-Headers", "Apiproxy-Session-Id")

答案 1 :(得分:0)

尝试添加responseType: 'text'

this.http.post('http://localhost:8081/user/login', 
    JSON.stringify(requestBody), {observe: 'response', responseType: 'text'}).subscribe(resp => {
        console.log(resp);
    });