3

I'm unable to change the headers when doing a post request with http module in Angular (with Ionic). Here is my code:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

const apiUrl = "https://webhook.site/c2d56330-84d4-47cf-9f98-472f7eac8000";

@Injectable({
  providedIn: 'root'
})
export class APIService {

  constructor(private http: HttpClient) { }

  getToken(){
    var body = {
      'data1': 'data2',
      'somedata3': 'data4',
  };
  let headers = new HttpHeaders().append('Content-Type', 'application/json');

  this.http.post(apiUrl, JSON.stringify(body), {headers}).subscribe(data =>
    console.log(data));

  console.log(headers.get('Content-Type')); //return 'application/json'
  }
}

Everything works well, but it still sends header "content-type: text/plain" instead of "content-type: application/json".

Do I type something wrong?

ypxo
  • 31
  • 2

1 Answers1

2

I'd prefer something like:

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

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json'
  })
};
this.http.post<Foo>(this.apiUrl, body, httpOptions)

Also I don't see a need to stringify the body, just pass it as a "normal" object

Anton Sarov
  • 3,712
  • 3
  • 31
  • 48
  • Thanks for reply. If I pass body without JSON.stringify, it will send only empty request without any data. – ypxo Feb 24 '19 at 21:36