Angular2的Http.post在POST方法调用的响应中未返回标头

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)时,我得到了准确的响应,但是这次是(所有)期望的标头,包括Location响应标头.

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?

提醒您:在此示例中,我的服务返回了可观察到的响应".这不是返回给调用者的预期类类型.我使用它的目的是为了方便了解发帖后的情况.实际上,我打算传递存储在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,否则返回的标头将不适用于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.

如果响应实际上包含标题,您可以在浏览器的devtools(网络标签AFARK)中调查请求响应?

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