简体   繁体   中英

Angular2 HTTP request not appending headers

In my application, I am trying to send a quick test request to my API to test my authentication. When a button is clicked, this function is called, which creates an Authorization header and makes an HTTP request:

  public test() {
    const headers: Headers = new Headers();
    headers.append('Authorization', 'Bearer ' + this.auth.token);
    this.http.get('http://localhost:62940/api/ping/secure', { headers: headers }).subscribe(x => {
      console.log(x);
    });
  }

However, when I'm debugging (or analyzing traffic using Fiddler), headers has the header that I created, but nothing is being appended to the Http request.

You have to use RequestOptions and append header to.

let headers = new Headers();

headers.append('Authorization', 'Bearer ' + this.auth.token);
let options = new RequestOptions({headers: headers});
this.http.get(URL, options).subscribe(x => {
     console.log(x);
});

Take a look at: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials

If you are making a CORS request, you need to add the "withCredentials: true" RequestOption with the HTTP request. Otherwise, authorization headers will not be added with the request.

public test() {
   const headers: Headers = new Headers();
   headers.append('Authorization', 'Bearer ' + this.auth.token);
   this.http.get('http://localhost:62940/api/ping/secure', {
      withCredentials: true,
      headers: headers
   }).subscribe(x => {
       console.log(x);
   });
}

You also need to make sure that your server will accept the Authorization header by adding an "Acess-Control-Allow-Credentials = true" header to the pre-flight response, though this is different from server to server. Also, make sure CORS is enabled on the server as well.

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