How to set headers to application/json in Angular 2

Viewed 20876

I am trying to send HTTP post request in Angular 2 but not able to set headers to content type application JSON.

My code is:

login(url,postdata)
{
    var headers = new Headers({'Content-Type': 'application/json'});
    return this._http.post(url,JSON.stringify(postdata),this.headers)
    .map(res => res.json())    
}

When I checked in network I found that Content-Type is set as text/plain and thus server is not receiving any data. Any suggestions will be appreciated.

5 Answers

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();

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});
  }
}
Related