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?

2

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for reply. If I pass body without JSON.stringify, it will send only empty request without any data.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.