Adding a HTTP header to the Angular HttpClient doesn't send the header, why?

349,590

Solution 1

The instances of the new HttpHeader class are immutable objects. Invoking class methods will return a new instance as result. So basically, you need to do the following:

let headers = new HttpHeaders();
headers = headers.set('Content-Type', 'application/json; charset=utf-8');

or

const headers = new HttpHeaders({'Content-Type':'application/json; charset=utf-8'});

Update: adding multiple headers

let headers = new HttpHeaders();
headers = headers.set('h1', 'v1').set('h2','v2');

or

const headers = new HttpHeaders({'h1':'v1','h2':'v2'});

Update: accept object map for HttpClient headers & params

Since 5.0.0-beta.6 is now possible to skip the creation of a HttpHeaders object an directly pass an object map as argument. So now its possible to do the following:

http.get('someurl',{
   headers: {'header1':'value1','header2':'value2'}
});

Solution 2

To add multiples params or headers you can do the following:

constructor(private _http: HttpClient) {}

//....

const url = `${environment.APP_API}/api/request`;

let headers = new HttpHeaders().set('header1', hvalue1); // create header object
headers = headers.append('header2', hvalue2); // add a new header, creating a new object
headers = headers.append('header3', hvalue3); // add another header

let params = new HttpParams().set('param1', value1); // create params object
params = params.append('param2', value2); // add a new param, creating a new object
params = params.append('param3', value3); // add another param 

return this._http.get<any[]>(url, { headers: headers, params: params })

Solution 3

set http headers like below in your http request

return this.http.get(url, { headers: new HttpHeaders({'Authorization': 'Bearer ' + token})
 });

Solution 4

I was with Angular 8 and the only thing which worked for me was this:

  getCustomHeaders(): HttpHeaders {
    const headers = new HttpHeaders()
      .set('Content-Type', 'application/json')
      .set('Api-Key', 'xxx');
    return headers;
  }

Solution 5

I struggled with this for a long time. I am using Angular 6 and I found that

let headers = new HttpHeaders();
headers = headers.append('key', 'value');

did not work. But what did work was

let headers = new HttpHeaders().append('key', 'value');

did, which makes sense when you realize they are immutable. So having created a header you can't add to it. I haven't tried it, but I suspect

let headers = new HttpHeaders();
let headers1 = headers.append('key', 'value');

would work too.

Share:
349,590

Related videos on Youtube

Frennetix
Author by

Frennetix

Updated on February 23, 2021

Comments

  • Frennetix
    Frennetix about 3 years

    Here is my code:

    import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
    

    logIn(username: string, password: string) {
        const url = 'http://server.com/index.php';
        const body = JSON.stringify({username: username,
                                     password: password});
        const headers = new HttpHeaders();
        headers.set('Content-Type', 'application/json; charset=utf-8');
        this.http.post(url, body, {headers: headers}).subscribe(
            (data) => {
                console.log(data);
            },
            (err: HttpErrorResponse) => {
                if (err.error instanceof Error) {
                    console.log('Client-side error occured.');
                } else {
                    console.log('Server-side error occured.');
                }
            }
        );
    }
    

    and here the network debug:

    Request Method:POST
    Status Code:200 OK
    Accept:application/json, text/plain, */*
    Accept-Encoding:gzip, deflate
    Accept-Language:en-US,en;q=0.8
    Cache-Control:no-cache
    Connection:keep-alive
    Content-Length:46
    Content-Type:text/plain
    

    and Data are stored in 'Request Payload' but in my server doesn't received the POST values:

    print_r($_POST);
    Array
    (
    )
    

    I believe the error comes from the header not set during the POST, what did I do wrong?

    • Frennetix
      Frennetix almost 7 years
      Yes, thanks! But after not receiving data on my Back-end, I went to application/x-www-form-urlencoded. Anyway the main question is anserwerd
  • tishma
    tishma over 6 years
    Interesting. So, for us coming from OO world, set method name is somewhat misleading.
  • Stefan Falk
    Stefan Falk over 6 years
    What if I want to set multiple headers? I've tried to chain the comment HttpHeaders().set(..).set(..) but now again the headers are not getting written to the HTTP header fields?!
  • Jota.Toledo
    Jota.Toledo over 6 years
    It should work fine according to the src github.com/angular/angular/blob/master/packages/common/http/‌​src/… . I cant help you any further without more information about your issue (code)
  • Jago
    Jago over 6 years
    This method does not seem to work either. I mean, you can add the headers, and they will show in the lazyUpdate property, but eventually it will crash with the CreateListFromArrayLike exception when making the request effective by subscribing to it.
  • Benson
    Benson over 6 years
    To add multiple headers use: headers:HttpHeaders = new HttpHeaders({ 'Application-Id': this.appId, "REST-API-Key": this.apiKey, "Content-Type": "application/json" });
  • Melroy van den Berg
    Melroy van den Berg about 6 years
    So in my case I made an mistake by switching headers & params in the list of arguments to a function (since both accepted a json object). Meaning just watch out for mistakes, and HttpHeaders as type is a good practice after all.. Off-topic: when you can use objects everywhere, don't use TypeScript but VanillaJS.
  • Drellgor
    Drellgor almost 6 years
    Why have headers and requests been made immutable? angular.io/guide/http#immutability
  • hygull
    hygull almost 6 years
    I am using Angular 6. After setting headers also, I am getting Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:4200' is therefore not allowed access. The response had HTTP status code 403. properties.component.ts:23 GOT ERROR:- on console. Can someone please suggest any solution?
  • hygull
    hygull almost 6 years
    I have already tried many methods. Changed the syntaxes of HttpHeaders values. Also checked angular.io. I am able to make API call and get the response if there is no AUTH. I am getting the above error in case of BASIC authentication.
  • mast3rd3mon
    mast3rd3mon over 5 years
    As an important update, as of Angular 6.1.7, you cant use .set() either
  • Jota.Toledo
    Jota.Toledo over 5 years
    @mast3rd3mon Its still part of the public API angular.io/api/common/http/HttpHeaders#set
  • mast3rd3mon
    mast3rd3mon over 5 years
    @Jota.Toledo so is .append() but they only work when chained. new HttpDeaders().set() works but let header = new HttpHeaders(); header.set() doesnt
  • Jota.Toledo
    Jota.Toledo over 5 years
    @mast3rd3mon Both append and set return new instances with the changes applied, as I explain in my answer. How is that related to your previous comment? I think you should remove your comment, as you are making an incorrect assertion.
  • mast3rd3mon
    mast3rd3mon over 5 years
    @Jota.Toledo i wont remove my comment as it will help others, you either need to pass the headers into the HttpHeader constructor or call .set() or .append() directly from the new HttpHeader()
  • Jota.Toledo
    Jota.Toledo over 5 years
    lol thats exactly what I described in my answer. Whatever, just notice that "as of 6.1.7, you cant uset .set()" is an wrong assertion, or poorly explained.
  • mast3rd3mon
    mast3rd3mon over 5 years
    @Jota.Toledo ill rephrase, you cant use .set() and .append() without it being direct onto the constructor method
  • Ruan Mendes
    Ruan Mendes over 5 years
  • Ruan Mendes
    Ruan Mendes over 5 years
    Your first attempt should work, you're assigning the result of the append to the headers variable. Right now your explanation doesn't make any sense, specially your last guess that adding a let may fix it
  • Ojonugwa Jude Ochalifu
    Ojonugwa Jude Ochalifu over 4 years
    Is it me or is this kinda overkill for the question asked?
  • Jota.Toledo
    Jota.Toledo over 4 years
    This isn't attempting to answer OPs question. Its just a bunch of code with no explanation whatsoever.
  • lyolikaa
    lyolikaa about 4 years
    option const headers = new HttpHeaders({'Content-Type':'application/json; charset=utf-8'}); doesn't work, at least on Angular 9 my implementation : let headers = new HttpHeaders().set('Content-Type','text/xml;charset=UTF-8').s‌​et...
  • Aakash Kumar
    Aakash Kumar over 3 years
    This is not even close to context. It looks like self-promotion.
  • Md. Abu Zaman
    Md. Abu Zaman about 3 years
    how you get the token?