Angular 4 : Send custom headers with http requests

4.9k views Asked by At

In Angular 4, I am unable to send custom header with http requests.

I have tried to send header using following code:

let response = this.http.post(environment.serverUrl + url, data, this.getHeaders())
      .map((response: Response) => response.json())
      .catch(this.handleError);

private getHeaders(): RequestOptions {
    let reqOp = new RequestOptions();

    let headers = new Headers();
    headers.append('Accept', 'application/json');
    headers.append('Access-Control-Allow-Origin', '*');
    headers.append('Access-Control-Allow-Headers', '*');

    reqOp.headers = headers;

    return reqOp;
  }

Still the headers are not appending to my request header. If I inspect the call in "Network" of Chrome then I am not able to see the custom headers.

Accept:*/*
Accept-Encoding:gzip, deflate
Accept-Language:en-GB,en-US;q=0.8,en;q=0.6
Access-Control-Request-Headers:access-control-allow-headers,access-control-allow-origin,content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:10.xxx.xxx.xxx:3300
Origin:http://localhost:4200
Referer:http://localhost:4200/
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36

Any help to resolve this? Please note I am not using HttpClient from '@angular/common/http';

1

There are 1 answers

2
Suhel On

Do like this. If want more headers just add it to the array of header.

apiUrl = 'api/url'
myFunction(data) {
  let headers = new Headers({'Content-Type':'application/json'});
  let options = new RequestOptions({headers: headers});

  return this.http.post(this.apiUrl, JSON.stringify(data), options).map((response: Response) => {
    return response.json()
  })
}