user10745471
user10745471

Reputation:

Angular 6: Unable to set Content-Type of http Header correctly

I'm trying to make a post call using HttpHeader in angular 6 And I set Content-Type to application/json. But the server get x-www-form-urlencoded instead of application/json for Content-Type.

service.ts

   
myFunction(id: string, name: string, fields: string[]) {
  const body = {
    id: id,
    name: name,
    fields: fields
  };
  let headers = new HttpHeaders();
  headers= headers.set('content-type', 'application/json');
  return this.http.post(this.URL , body, {headers});
}

component.ts

submit(){
  this.myService.myFunction(this.id, this.form.value.name,  
  this.form.value.fields).subscribe((res:any) => {
    console.log(this.form);
  }, error => {
    console.log(JSON.parse(error.error).errors);
  })
}

Upvotes: 10

Views: 31578

Answers (2)

Rahul
Rahul

Reputation: 2128

Just use append function to add new headers and finally set the headers on options

Try something like this,

let headers = new HttpHeaders();
headers= headers.append('content-type', 'application/json');
return this.http.post(this.URL, body, {headers : header});

If it doesn't work try to add header like this,

let headers = new HttpHeaders({'content-type': 'application/json'});

Hope it helps. Happy coding :)

Upvotes: 8

MesutAtasoy
MesutAtasoy

Reputation: 822

You need to set headers in option.

return this.http.post(this.URL , body, {headers : new HttpHeaders({ 'Content-Type': 'application/json' })});

Upvotes: 18

Related Questions