Search code examples
angularangular-httpclient

Angular 10 HttpClient unable to add body and header


Using Angular 10 and HttpClient with following data:

const data = {
  'username': username,
  'password': password
};
const headers = { 'content-type': 'application/json'}

const body = JSON.stringify(data);
return this.httpClient.post(endPointURL, body,{'headers':headers})

On endPointURL I can see body details as null. But if I remove header like this:

return this.httpClient.post(endPointURL, body)

I can see body details correct. I need to implement body data and header. Could you please let me know what am I doing wrong?


Solution

  • Create the headers as -

    let headers = new HttpHeaders({
        'Content-Type': 'application/json'
        });
    
    // OR,
    let headers = new HttpHeaders().set('Content-Type', 'application/json');
    

    and pass it as {headers: headers}.

    Also, you don't need to JSON.stringify the data.

    Try something like -

    const data = {
      'username': username,
      'password': password
    };
    
    let headers = new HttpHeaders({
        'Content-Type': 'application/json'
        });
    
    return this.httpClient.post(endPointURL, data, {headers: headers});