Angular 10 HttpClient unable to add body and header

Viewed 281

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?

2 Answers

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

Follow the steps.

  1.     import { HttpClient, HttpHeaders } from "@angular/common/http";
    
  2.     const headers = { headers: new HttpHeaders({"Content-Type":"application/json"})}
        const body= { 'username': username, 'password': password};
    
  3.       return this.httpClient.post(endPointURL, body,headers)
    
Related