Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I add Headers to http.get or http.post in Typescript and angular 2?

getHeroes (): Observable<Heros[]> {     return this.http.get(this.heroesUrl)       .map(this.extractData)       .catch(this.handleError);   } 

Where I add the headers and how? looking for a simple example.

like image 586
AngularOne Avatar asked Feb 20 '17 19:02

AngularOne


People also ask

How do I add headers in HTTP request in Angular 8?

There are two ways by which we can add the headers. One, we add the HTTP Headers while making a request. The second way is to use the HTTP interceptor to intercept all the Requests and add the Headers. In both cases, we use the httpHeaders configuration option provided by angular HttpClient to add the headers.

Can you add custom HTTP headers?

If you want to set a custom HTTP headers on your server to be sent in your HTTP responses, the process is quite simple. We have outlined below the snippets required to add a custom header for both Apache and Nginx web servers.

Why do we use HTTP headers in Angular?

Http headers is need to authenticate the request, if you have token in your header and the backend will verify your API to check if you are authenticate to get the Response.


1 Answers

You can define a Headers object with a dictionary of HTTP key/value pairs, and then pass it in as an argument to http.get() and http.post() like this:

const headerDict = {   'Content-Type': 'application/json',   'Accept': 'application/json',   'Access-Control-Allow-Headers': 'Content-Type', }  const requestOptions = {                                                                                                                                                                                    headers: new Headers(headerDict),  };  return this.http.get(this.heroesUrl, requestOptions) 

Or, if it's a POST request:

const data = JSON.stringify(heroData); return this.http.post(this.heroesUrl, data, requestOptions); 

Since Angular 7 and up you have to use HttpHeaders class instead of Headers:

const requestOptions = {                                                                                                                                                                                    headers: new HttpHeaders(headerDict),  }; 
like image 75
HuntedCodes Avatar answered Oct 07 '22 15:10

HuntedCodes