简体   繁体   中英

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

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

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM