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

8

50
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.

Bastinado answered 20/2, 2017 at 19:32 Comment(0)
G
99

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), 
};
Groundsill answered 20/2, 2017 at 19:40 Comment(5)
thank you. I'm getting -Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. OriginBastinado
Check out the MDN documentation on CORS and preflight requests. If you're still having issues, ask another question. :)Groundsill
Thank you HuntedCodes. It's helped me to fixed issue for pass headers in POST or GET. Especially 'Access-Control-Allow-Headers', this helps me to prevent the error from disabling web security.Arvell
working with Angular 7, you need to use the type HttpHeaders instead of HeadersHawkeyed
not working for me with angular 5. Options call made but not GetAletheaalethia
L
5

Be sure to declare HttpHeaders without null values.

    this.http.get('url', {headers: new HttpHeaders({'a': a || '', 'b': b || ''}))

Otherwise, if you try to add a null value to HttpHeaders it will give you an error.

Latialatices answered 17/12, 2020 at 14:21 Comment(1)
this.http.get('url', headers: new HttpHeaders({ 'ApiKey': 'P@ssw0rd', 'DbName': 'MES-QTY' })})Singley
P
3

I have used below code in Angular 9. note that it is using http class instead of normal httpClient.

  1. so import Headers from the module, otherwise Headers will be mistaken by typescript headers interface and gives error

    import {Http, Headers, RequestOptionsArgs } from "@angular/http";

  2. and in your method use following sample code and it is breaked down for easier understanding.

    let customHeaders = new Headers({ Authorization: "Bearer " + localStorage.getItem("token")});
    const requestOptions: RequestOptionsArgs = { headers: customHeaders };
    return this.http.get("/api/orders", requestOptions);
    
Penney answered 29/3, 2020 at 16:0 Comment(2)
Isn't @angular/http deprecated?Bashemath
@Bashemath maybe. They are changing fast. at that time it was working without problemPenney
R
0

This way I was able to call MyService

private REST_API_SERVER = 'http://localhost:4040/abc';

public sendGetRequest() {
  const myFormData = { email: '[email protected]', password: '123' };
  const headers = new HttpHeaders();
  headers.append('Content-Type', 'application/json');

  this.httpClient.post(this.REST_API_SERVER, myFormData, {
    headers: headers,
  })
  .subscribe((data) => {
    console.log(data, myFormData, headers);
    return data;
  });
}
Remonaremonetize answered 7/12, 2020 at 13:1 Comment(0)
S
0

This is my version from Angular 13 (2+ & services!) using RXJS subscribe, setting a header for getting data in a different language, where the backend looks for the "lang" header that's set, so easily adaptable for any scenario where you want to send custom headers. Of course you need to do something with them server-side.

The service is called from the component with a parameter that sets a value in the header, that value being passed in as a function argument, in this case "language".
As you can see, the httpOptions new headers is just added to the GET, after the path/params, comma separated.

myService.service.ts :

export class MyService {

  const serverUrl = 'my-site/api';  

  getSomethingById(language: string, id: string): Observable<any> {
    let httpOptions = {
      headers: new HttpHeaders({
        'lang': language,
      })
    }

    return this.httpClient.get<string>(`${this.serverUrl}/endpointname/${id}`, httpOptions).pipe(
      catchError((err) => {
        throw '1234. Request failed:' + err;
    })
  )
}

my.component.ts

changeLanguage(selectValue: string) {
  let language = 'gb-en';
  if (selectValue === 'Spanish') {
    language = 'ca-es';
  } else if (selectValue == 'American') {
    language = 'gb-en';
  }

    // the important bit: 
  this.myService.getSomethingById(language, this.id).subscribe({
    next: (res) => {
      this.variableName = res;
    },
    error: (error) => {
      console.error('5678:', error);
    },
    complete: () => {
      this.callMyOtherFunction();
    },
  })
}
Soler answered 17/11, 2022 at 10:46 Comment(0)
R
0

This soloution for angular 17

Do this step to use http service for standalone component.

  1. Open Main.ts file
  2. Import provideHttpClient from angular common module as below.

import {provideHttpClient} from '@angular/common/http';

  1. add provideHttpClient() in providers array. as below bootstrapApplication(AppComponent, { providers: [provideHttpClient()] })
Rotter answered 19/3 at 9:6 Comment(0)
S
-1
this.http.get('url',  headers: new HttpHeaders({ 'ApiKey': 'P@ssw0rd', 'DbName': 'MES-QTY'})})

Please Try this..! it's Worked for me..!

Singley answered 10/7, 2022 at 7:8 Comment(0)
W
-8

if someone facing issue of CORS not working in mobile browser or mobile applications, you can set ALLOWED_HOSTS = ["your host ip"] in backend servers where your rest api exists, here your host ip is external ip to access ionic , like External: http://192.168.1.120:8100

After that in ionic type script make post or get using IP of backened server

in my case i used django rest framwork and i started server as:- python manage.py runserver 192.168.1.120:8000

and used this ip in ionic get and post calls of rest api

Watteau answered 24/8, 2018 at 12:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.