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

笑着哭i 提交于 2020-03-23 08:19:09

问题


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

回答1:


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

Try something like this

let header = 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 header = new HttpHeaders({'content-type': 'application/json'});

Hope it helps - happy coding :)




回答2:


You need to set headers in option.

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


来源:https://stackoverflow.com/questions/53618872/angular-6-unable-to-set-content-type-of-http-header-correctly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!