Angular2 's Http.post is not returning headers

2019-04-01 04:31发布

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.

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.

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

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));
 }

1条回答
爷的心禁止访问
2楼-- · 2019-04-01 05:06

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

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

查看更多
登录 后发表回答