角度6:无法正确设置HTTP标头的内容类型

时间:2018-12-04 17:57:43

标签: angular http-headers content-type

我正在尝试使用Angular 6中的HttpHeader进行发布呼叫,并将Content-Type设置为application / json。 但是服务器获取Content-Type的x-www-form-urlencoded而不是application / json。

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

2 个答案:

答案 0 :(得分:2)

您需要在选项中设置标题。

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

答案 1 :(得分:1)

只需使用append函数添加新标题,然后最后在选项上设置标题

尝试这样的事情

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

如果不起作用,请尝试添加这样的标题

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

希望有帮助-编码愉快:)