Angular2 's Http.post is not returning headers in the response of a POST method invocation

拈花ヽ惹草 提交于 2019-12-05 02:28: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:


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?



来源:https://stackoverflow.com/questions/40508187/angular2-s-http-post-is-not-returning-headers-in-the-response-of-a-post-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!