Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
808 views
in Technique[技术] by (71.8m points)

rest - Can't read custom header in HttpResponse from HttpClient in a Ionic Angular application

I'm requesting an endpoint that creates a new resource and returns a 201 response containing a "Location" header with the newly created resource:

Network inspecting on Chrome

However, when I try to get header value as described in Angular guide, I get a "null" value instead of the actual value. Here is my code (note: I'm setting responseType:'text' to avoid Json parsing error as the response body is empty):

(...)
import { HttpClient } from '@angular/common/http';

(...)

  constructor(public navCtrl: NavController, public navParams: NavParams, public http: HttpClient) {
  }

  ionViewDidLoad() {
    let obj = {nome : "SomeName"}
    this.http.post("http://localhost:8080/categorias", obj, {observe: 'response', responseType: 'text'})
    .subscribe(
        (resp) => {
          console.log(resp.headers.get('Location'));
        }
      );
  }

I even tried console.log(resp.headers) in order to check this object, and it shows a completely different structure:

enter image description here

How can I get a custom header from a HttpResponse object from the new HttpClient Angular API?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I encountered a similar issue with the eTag header : this is a Cross Origin issue.

From what I remember, CORS return only a couple of simple headers, such as Cache-Control, Content-Language, Content-Type, Expires, Last-Modified, etc.

If you want to return a specific header, you have to add another header, Access-Control-Expose-Headers, containing a list of the headers you want to return with it. So, in your case, Access-Control-Expose-Headers = 'location'.

You also obvioulsy need to change your backend to return the same header to Angular.

Hope this helps !


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...