Angular 6:无法正确设置 http Header 的 Content-Type

a-m*_*a-m 7 content-type http-headers angular

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

服务.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});
}
Run Code Online (Sandbox Code Playgroud)

组件.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);
  })
}
Run Code Online (Sandbox Code Playgroud)

Off*_*sut 13

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

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


Rah*_*hul 8

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

尝试这样的事情

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

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

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

希望它有所帮助 - 快乐编码:)