Search code examples
angulartypescriptpostheader

How to set headers to application/json in Angular 2


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.


Solution

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