Search code examples
angularheaderangular-services

Angular 10 append X-Requested-With: XMLHttpRequest to the header


I wrote an angular service that calls an old API. I need to format the header to look like the following, where the 'X-Requested-With' shows at the bottom (this is a requirement, not by choice). Here's an image of the original request:

enter image description here

Here's is a snippet of my code, which does run and returns a status of 200:

  private _headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded; 
   charset=UTF-8');
  myRequest(data: string): Observable<string> {
    return this.http.post<string>(this.url, data, { headers: this._headers });
  }

What is correct way to append the X-Requested-With: XMLHttpRequest to the header. Thanks for the help. This is an image of what I get so far:

enter image description here


Solution

  • HttpHeaders in Angular are immutable

    This means you can set your X-Requested-With header in your myRequest function.

    myRequest(data: string): Observable<string> {
      const headers = this._headers.set('X-Requested-With', 'XMLHttpRequest');
      return this.http.post<string>(this.url, data, { headers });
    }
    

    It won't change your private _headers.

    You can inspect the headers in this example