Angular 2 http Observable请求不返回响应头 [英] Angular 2 http Observable request not returning response header

查看:880
本文介绍了Angular 2 http Observable请求不返回响应头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Angular 2.2.3并使用带有rxjs的observable进行http请求。标题显示在Chrome控制台中,但响应中标题对象上的标题列表为空。
以下是代码:

I am using Angular 2.2.3 and doing http requests with observables with rxjs. The headers appear in the Chrome console, but the list of headers on the headers object from the response is empty. Here is the code :

登录功能

login(body: Object): Observable<Response> {
    return this.http.post(this.url, body);
}

订阅可观察的登录功能调用

this.authService.login(values).subscribe(res => {
    console.log(res.headers.get("Authorization"))
    console.log(res)
},
err => {
    console.log(err);
});

我做错了什么或我应该做些什么?

Is there something I am doing wrong or that I should do differently?

Chrome网络控制台响应标题

Console.log结果

null value是 res.headers.get(授权)
如您所见,标题列表是空的。

The null value is res.headers.get("Authorization") As you can see, the headers list is empty.

非常感谢您的帮助!

推荐答案

我找到了解决问题的方法。事实证明,Angular在幕后使用了 XMLHttpRequest 。因此,可以以编程方式(使用Angular的函数)显示给客户端的标题必须位于标题列表中 Access-Control-Expose-Headers 。当我们将请求发送回客户端时,必须在后端创建此列表。以下是我使用ExpressJS启用授权标题的方法:

I have found the solution to my problem. It turns out that Angular uses an XMLHttpRequest behind the scenes. Because of that, the headers that can be shown to the client "programmatically" (with Angular's function) have to be in the list of the header Access-Control-Expose-Headers. This list has to be created in the backend when we send the request back to the client. Here is what I did with ExpressJS to enable the Authorization header:

app.use((req, res, next) => {
  // List of headers that are to be exposed to the XHR front-end object
  res.header('Access-Control-Expose-Headers', 'Authorization');
  next();
});

我在前端的初始代码与控制台保持一致。现在出现授权标题的日志

My initial code in the front-end stayed the same and the console.log of the Authorization header now appears.

解释我们为什么需要此标题的文档

整个文档非常有趣,我认为我在API方面相当不错,但在阅读本文时我学到了很多东西: - )

This whole documentation is very interesting, I thought I was pretty good in APIs, but I learned a lot while reading this :-)

这篇关于Angular 2 http Observable请求不返回响应头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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