Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Angular 2 http Observable request not returning response header

I am using Angular 2.2.3 and doing http requests with observables with rxjs. The headers appear in the Chrome console, but the list of headers on the headers object from the response is empty. Here is the code :

Login function

login(body: Object): Observable<Response> {
    return this.http.post(this.url, body);
}

Call of login function with subscription to the observable

this.authService.login(values).subscribe(res => {
    console.log(res.headers.get("Authorization"))
    console.log(res)
},
err => {
    console.log(err);
});

Is there something I am doing wrong or that I should do differently?

Chrome network console response headers

This is the response in the Chrome console where 'Authorization definitely exists'

Console.log results

The null value is res.headers.get("Authorization") As you can see, the headers list is empty. Chrome console

Thank you very much for your help!

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

I have found the solution to my problem. It turns out that Angular uses an XMLHttpRequest behind the scenes. Because of that, the headers that can be shown to the client "programmatically" (with Angular's function) have to be in the list of the header Access-Control-Expose-Headers. This list has to be created in the backend when we send the request back to the client. Here is what I did with ExpressJS to enable the Authorization header:

app.use((req, res, next) => {
  // List of headers that are to be exposed to the XHR front-end object
  res.header('Access-Control-Expose-Headers', 'Authorization');
  next();
});

My initial code in the front-end stayed the same and the console.log of the Authorization header now appears.

Documentation explaining why we need this header

This whole documentation is very interesting, I thought I was pretty good in APIs, but I learned a lot while reading this :-)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...