Reputation: 31
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?
Upvotes: 3
Views: 472
Reputation: 3748
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
Upvotes: 2