Adding a HTTP header to the Angular HttpClient doesn't send the header, why?
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.
Related videos on Youtube
Frennetix
Updated on February 23, 2021Comments
-
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 almost 7 yearsYes, 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 over 6 yearsInteresting. So, for us coming from OO world,
set
method name is somewhat misleading. -
Stefan Falk over 6 yearsWhat 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 over 6 yearsIt 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 over 6 yearsThis 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 theCreateListFromArrayLike
exception when making the request effective by subscribing to it. -
Benson over 6 yearsTo 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 about 6 yearsSo 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 almost 6 yearsWhy have headers and requests been made immutable? angular.io/guide/http#immutability
-
hygull almost 6 yearsI 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 almost 6 yearsI 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 over 5 yearsAs an important update, as of Angular 6.1.7, you cant use
.set()
either -
Jota.Toledo over 5 years@mast3rd3mon Its still part of the public API angular.io/api/common/http/HttpHeaders#set
-
mast3rd3mon over 5 years@Jota.Toledo so is
.append()
but they only work when chained.new HttpDeaders().set()
works butlet header = new HttpHeaders(); header.set()
doesnt -
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 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 thenew HttpHeader()
-
Jota.Toledo over 5 yearslol 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 over 5 years@Jota.Toledo ill rephrase, you cant use
.set()
and.append()
without it being direct onto the constructor method -
Ruan Mendes over 5 yearsSilly to make it not behave like developer.mozilla.org/en-US/docs/Web/API/Headers/append
-
Ruan Mendes over 5 yearsYour 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 over 4 yearsIs it me or is this kinda overkill for the question asked?
-
Jota.Toledo over 4 yearsThis isn't attempting to answer OPs question. Its just a bunch of code with no explanation whatsoever.
-
lyolikaa about 4 yearsoption 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').set...
-
Aakash Kumar over 3 yearsThis is not even close to context. It looks like self-promotion.
-
Md. Abu Zaman about 3 yearshow you get the token?