Angular2 的 Http.post 没有在 POST 方法调用的响应中返回标头 [英] Angular2 's Http.post is not returning headers in the response of a POST method invocation

查看:35
本文介绍了Angular2 的 Http.post 没有在 POST 方法调用的响应中返回标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在调用 REST 端点.我想添加一个资源(如下).但是,当我的服务调用 Http 的 post 方法时,它将调用请求但不返回响应的标头.至少,我遇到了 Response 实例的空标头对象.(??)我确实期待响应标头.特别是我希望 Location 标头作为REST ADD RESOURCE"模式的一部分.Location 标头包含新创建资源的 URL.

I am doing a call to a REST endpoint. I want to add a resource (below). However, when my service calls Http's post method it will invoke the request but the response's header(s) are not returned. At least, I experience an empty headers object of the Response instance. (??) I do expect response header. In particular I expect the Location header as part of a "REST ADD RESOURCE" pattern. The Location headers contains the URL of the newly created resource.

这件事很奇怪:当我直接调用我的 API 时(因此不是通过 Angular2),我得到了确切的响应,但这次使用(所有)预期的标头,包括位置响应标头.

The weird thing about this: when I call my API directly (thus not via Angular2), I get the exact response but this time with (all) expected headers including the Location response header.

呃,是 Http.post 有问题还是我做错了什么?

Uhh, is there something wrong with Http.post or am I doing something wrong?

请注意:在这个例子中,我的服务返回一个 Observable Response.这不是返回给调用者的预期类类型.我使用它是为了方便理解帖子响应发生了什么.实际上,我打算传递存储在 Location 标头中的 url.

Mind you: My service returns an Observable Response in this example. This is not the intended class type to return to the caller. I am using it for the convenience of understanding what is happening with the post response. In reality it is my intention to pass the url stored in the Location header.

addModel(model: any): Observable<Response> {
let token = this.loginService.auth.accessToken;
let headers = new Headers({
  'Content-Type': 'application/json',
  'Accept': 'application/json',
  'Authorization': `Bearer ${token}`
});
let options = new RequestOptions({headers: headers});
let data: string = JSON.stringify(model);
return this.http.post(this.url, data, options)

  // .map(r => {
  //   console.log("Response ", r);
  //   return r.headers.get("Location"); // THERE IS NOTHING IN headers (?). Don't understand.
  // })
  .catch(err => Observable.throw(err));
 }

推荐答案

对于 CORS 请求,服务器需要添加 Allow-access-expose-headers: headername 否则返回的 headers 将不会JS 可用.

With a CORS request the server needs to add Allow-access-expose-headers: headername otherwise the returned headers won't be available to JS.

如果响应实际上包含标头,您可以在浏览器开发工具(网络选项卡 AFARK)中调查请求响应吗?

You can investigate the request response in the browsers devtools (network tab AFARK) if the response actually contains the headers?

这篇关于Angular2 的 Http.post 没有在 POST 方法调用的响应中返回标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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