HTTP Headers In Angular
In this article, we will learn how to add HTTP Headers to an HTTP request in Angular. The headers can be added in one of two ways. One, while making a request, we add the HTTP Headers. The second method is to intercept all requests and add headers using an HTTP interceptor. To add the headers in both circumstances, we use the httpHeaders configuration option given by angular HttpClient.
HTTP Headers allow the client and server to exchange additional data about the HTTP request or response. The content-type header, for example, is used to specify the resource's media type, such as JSON, text, or blob. Another key element is the Authorization header 'Authorization', '<Bearer yourTokenhere>', which is used to communicate the bearer token.
HTTP Headers
The HttpHeaders helper class is used to add HTTP headers. It is one of the arguments supplied to the GET, POST, PUT, DELETE, PATCH, and OPTIONS requests.
You must import HttpHeaders into your component or service to use it in your project.
import { HttpHeaders } from '@angular/common/http';
const headers= new HttpHeaders() .set('content-type', 'application/json') .set('Access-Control-Allow-Origin', '*');
Then call the httpClient.get method passing the header as a parameter.
return this.httpClient.get(this.baseURL + 'users/' + userName + '/repos', { 'headers': headers })
set
set(name: string, value: string | string[]): HttpHeaders
After altering the provided header, the Sets function returns a new instance. If the header already exists, the value in the returned object is replaced with the specified value.
const headers = new HttpHeaders() .set('content-type', 'application/json') .set('Access-Control-Allow-Origin', '*');
HTTP Headers are immutable
let headers = new HttpHeaders() headers .set('content-type', 'application/json') headers .set('Access-Control-Allow-Origin', '*') console.log(headers);
You can use the code below as a workaround.
const headers= new HttpHeaders() .set('content-type', 'application/json') .set('Access-Control-Allow-Origin', '*');
You can also use the code below.
let headers = new HttpHeaders() headers=headers.set('content-type','application/json') headers=headers.set('Access-Control-Allow-Origin', '*'); console.log(headers)
append
append(name: string, value: string | string[]): HttpHeaders
The append method returns a new instance after appending a new value to the existing collection of values for a header. The append method does not do a check to see if the value already exists.
let headers = new HttpHeaders() headers=headers.append('content-type','application/json') headers=headers.append('Access-Control-Allow-Origin', '*') headers=headers.append('content-type','application/x-www-form-urlencoded') console.log(headers)
has
has(name: string): boolean
If the supplied header with the given name already exists in the HttpHeaders, returns true. The code below checks for the presence of the content-type header in the request header. If not, it will be added.
let headers = new HttpHeaders() headers=headers.append('Access-Control-Allow-Origin', '*') if (!headers.has('content-type')) { headers=headers.append('content-type','application/json') }
get
get(name: string): string | null
Get the first value for the specified header name, or null if none exists.
let headers = new HttpHeaders() .set('content-type','application/json') .set('Access-Control-Allow-Origin', '*') const h =headers.get('content-type') if (h==null) { console.log('content type header not present') } else { console.log(h) //returns 'application/json' }
getAll
getAll(name: string): string[] | null
Returns a list of all headers matching the provided header name, or null if none exist.
let headers = new HttpHeaders() .set('content-type','application/json') .set('Access-Control-Allow-Origin', '*') .append('content-type','application/x-www-form-urlencoded') const h =headers.getAll('content-type') console.log(h)
*** output
0: "application/json" 1: "application/x-www-form-urlencoded"
Keys
keys(): string[]
Get all of the request's headers.
let headers = new HttpHeaders() .set('content-type','application/json') .set('Access-Control-Allow-Origin', '*') .append('content-type','application/x-www-form-urlencoded') const h =headers.keys() console.log(h)
***output
0: "content-type" 1: "Access-Control-Allow-Origin"
delete
delete(name: string, value?: string | string[]): HttpHeaders
Removes the header and replaces it with the new headers. You can delete a header by providing the name or the name and value.
let headers = new HttpHeaders() .set('content-type','application/json') .set('Access-Control-Allow-Origin', '*') .append('content-type','application/x-www-form-urlencoded') headers=headers.delete("content-type","application/json") //delete content-type='application/json' headers=headers.delete("content-type") //delete all content-type headers
HTTP Headers from the object
let headers = new HttpHeaders({ 'Access-Control-Allow-Origin': '*','content-type': 'application/json'} ) console.log(headers)
Using HTTP Interceptor
HTTP Headers Example
npm install -g json-server
Create a db.json file with some information.
{ "people": [ { "id": 1, "name": "Don Bradman" }, { "id": 2, "name": "Sachin Tendulkar" } ] }
Start the server with the command below. http://localhost:3000/ will be the server's port.
json-server --watch db.json
export class Person { id:number name:string }
Now, open the app.module.ts file and put the following code:
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; import { FormsModule } from '@angular/forms' import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule, FormsModule, ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
Add the following code under the app.component.ts file:
import { Component, OnInit } from '@angular/core'; import { ApiService } from './api.service'; import { Person } from './person'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { title = 'http Headers Example'; people:Person[]; person = new Person(); constructor(private apiService:ApiService) {} ngOnInit() { this.refreshPeople() } refreshPeople() { this.apiService.getPeopleFromObject() .subscribe(data => { this.people=data; }) } addPerson() { this.apiService.addPerson(this.person) .subscribe(data => { this.person = new Person(); this.refreshPeople(); }) } }
Add the following code under the app.component.html file:
<h1>{{title}}</h1> <div> <div> <label>Name: </label> <input [(ngModel)]="person.name" /> </div> <div> <button (click)="addPerson()">Add</button> </div> </div> <button (click)="refreshPeople()">Refresh</button> <table class='table'> <thead> <tr> <th>ID</th> <th>Name</th> </tr> </thead> <tbody> <tr *ngFor="let person of people;"> <td>{{person.id}}</td> <td>{{person.name}}</td> </tr> </tbody> </table>
Add the following code under the app.routing.module.ts file:
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; const routes: Routes = []; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
Now, update the app.service.ts file using the following code:
import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Person } from './person'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class ApiService { baseURL: string = "http://localhost:3000/"; constructor(private http: HttpClient) { } getPeople(): Observable<Person[]> { console.log('getPeople ' + this.baseURL + 'people') return this.http.get<Person[]>(this.baseURL + 'people') } //Adding headers getPeopleWithHeaders(): Observable<Person[]> { const headers = { 'content-type': 'application/json'} console.log(headers) return this.http.get<Person[]>(this.baseURL + 'people',{'headers':headers}) } //Set method getPeopleWithSet(): Observable<Person[]> { const headers = new HttpHeaders() .set('content-type','application/json') .set('Access-Control-Allow-Origin', '*'); console.log(headers) return this.http.get<Person[]>(this.baseURL + 'people',{'headers':headers}) } //This wont work getPeopleWithImmutable(): Observable<Person[]> { const headers = new HttpHeaders() headers.set('content-type','application/json') headers.set('Access-Control-Allow-Origin', '*'); console.log(headers) return this.http.get<Person[]>(this.baseURL + 'people',{'headers':headers}) } getPeopleWithImmutable1(): Observable<Person[]> { let headers = new HttpHeaders() headers=headers.set('content-type','application/json') headers=headers.set('Access-Control-Allow-Origin', '*'); console.log(headers) return this.http.get<Person[]>(this.baseURL + 'people',{'headers':headers}) } getPeopleAppend(): Observable<Person[]> { let headers = new HttpHeaders() headers=headers.append('content-type','application/json') headers=headers.append('Access-Control-Allow-Origin', '*') headers=headers.append('content-type','application/x-www-form-urlencoded') headers=headers.append('customer-header', 'custom') console.log(headers) return this.http.get<Person[]>(this.baseURL + 'people',{'headers':headers}) } getPeopleHas(): Observable<Person[]> { let headers = new HttpHeaders() //headers=headers.append('content-type','application/json') headers=headers.append('Access-Control-Allow-Origin', '*') if (!headers.has('content-type')) { headers=headers.append('content-type','application/json') } console.log(headers) return this.http.get<Person[]>(this.baseURL + 'people',{'headers':headers}) } getPeopleGet(): Observable<Person[]> { let headers = new HttpHeaders() .set('content-type','application/json') .set('Access-Control-Allow-Origin', '*') const h =headers.get('content-type') if (h==null) { console.log('content type header not present') } else { console.log(h) } return this.http.get<Person[]>(this.baseURL + 'people',{'headers':headers}) } getPeopleGetAll(): Observable<Person[]> { let headers = new HttpHeaders() .set('content-type','application/json') .set('Access-Control-Allow-Origin', '*') .append('content-type','application/x-www-form-urlencoded') const h =headers.getAll('content-type') console.log(h) return this.http.get<Person[]>(this.baseURL + 'people',{'headers':headers}) } getPeopleKeys(): Observable<Person[]> { let headers = new HttpHeaders() .set('content-type','application/json') .set('Access-Control-Allow-Origin', '*') .append('content-type','application/x-www-form-urlencoded') const h =headers.keys() console.log(h) return this.http.get<Person[]>(this.baseURL + 'people',{'headers':headers}) } getPeopleDelete(): Observable<Person[]> { let headers = new HttpHeaders() .set('content-type','application/json') .set('Access-Control-Allow-Origin', '*') .append('content-type','application/x-www-form-urlencoded') headers=headers.delete('content-type','application/json') //headers=headers.delete("content-type") console.log(headers) return this.http.get<Person[]>(this.baseURL + 'people',{'headers':headers}) } getPeopleFromObject(): Observable<Person[]> { let headers = new HttpHeaders({ 'Access-Control-Allow-Origin': '*','content-type': 'application/json'} ) console.log(headers) return this.http.get<Person[]>(this.baseURL + 'people',{'headers':headers}) } addPerson(person:Person): Observable<Person> { const headers = { 'content-type': 'application/json'} const body=JSON.stringify(person); console.log(body) return this.http.post<Person>(this.baseURL + 'people', body,{'headers':headers}) } }