Unable to define custom headers using HttpHeaders on Angular 8

2.9k Views Asked by At

I am trying to run a GET request to SAP Business Objects which requires some custom headers. I followed Angular documentation to define the headers using HttpHeaders class but it seems like the custom headers (X-...) are not being recognized.

Here is my code to create the headers and run the GET request:

getEnvId(token: string) {

    this.tokenHdr = { 
      headers: new HttpHeaders({
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Accept-Language': 'en-US',
        'X-SAP-PVL': 'en-US',
        'X-SAP-LogonToken': token
      })
    }

    console.log(this.tokenHdr);

    return this._http.get('http://' + this.environment + '/biprws/infostore/cuid_' + this.reportCuid, this.tokenHdr)
  }

The console.log(this.tokenHdr) appears as follows: enter image description here

And the error response is: enter image description here

I am able to retrieve the token and pass it to this request, as I am able to successfully print the token to the console before this step. The token is retrieved via a POST request without any custom headers, so I am guessing the issue has something to do with the custom headers.

From Network tab in browser dev tools: enter image description here

2

There are 2 best solutions below

1
Damian C On BEST ANSWER

Try checking for any HttpInterceptors that are running on requests. Its possible your headers are being overwritten.

https://angular.io/guide/http#http-interceptors

2
shashi kumar On

try to do like this solve's your problem the set method returns headers object every time, you can do this. This way, original headers from the intercepted request will also be retained.

let headers = new HttpHeaders().set('Accept', 'application/json')
     .set('Content-Type' , 'application/json')
     .set('Accept-Language','en-US')
     .set('X-SAP-PVL', 'en-US')
     .set('X-SAP-LogonToken', token)

let apiUrl: string = 'http://url';

return this.http.get(apiUrl, {headers});

here what i did please check it may help

//for getting token

  loadToken() {
    const token = localStorage.getItem('token');
    this.authToken = token;
  }

 createAuthHeader() {
    this.loadToken();
    const headers = new HttpHeaders().set(
      'Authorization',
      `Bearer ${this.authToken}`
    );
    return { headers };
  }

  someTest() {
    return this.http.get(`${this.url}/count`, 
      this.createAuthHeader());
  }