I am trying to send HTTP post request in Angular2 but not able to set headers to content type application JSON.
My code is:
login(url,postdata)
{
Angular 9 version for 2020
export class ApiService {
private headers = new HttpHeaders({
'Content-Type': 'application/json',
});
constructor(
private http: HttpClient) {
}
get(path: string, params: HttpParams = new HttpParams()): Observable<any> {
return this.http.get(`${environment.apiUrl}${path}`, {params, headers: this.headers});
}
}
You should use code like this
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let options = new RequestOptions({ headers: headers });
return this.http.post(url, JSON.stringify(postdata), options).map(res => res.json());
Try this code:
private _getHeaders():Headers {
let header = new Headers({
'Content-Type': 'application/json'
});
return header;
}
public login(url, postdata){
let options = new RequestOptions({
headers: this._getHeaders()
});
return this.http.post(url, JSON.stringify(postdata),options).map(res => res.json());
}
change _http.post
parameters :
login(url,postdata) {
var headers = new Headers({'Content-Type': 'application/json'});
return this._http.post(url,postdata,{headers:headers})
.map(res => res.json())
}
Referencing the Angular 2 Angular Http Guide @angular/http has been deprecated, and @angular/common/http should be the one you are using in your Angular 2 App. Because if you do not specify http headers the default request will be sent as Content-Type text/plain, How you modify the http headers is to:
import { HttpClient, HttpHeaders } from '@angular/common/http';
.....
const req = this.http.post('/api/PostRequest/',
JSON.stringify(object),
{
headers:new HttpHeaders()
.set('Content-Type','application/json')
}).subscribe();