【问题标题】:Angular 6: Unable to set Content-Type of http Header correctlyAngular 6:无法正确设置 http Header 的 Content-Type
【发布时间】:2019-05-06 05:30:55
【问题描述】:

我正在尝试使用 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});
}

组件.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);
  })
}

【问题讨论】:

    标签: angular http-headers content-type


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      只需使用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'});

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

      【讨论】:

      • 我认为它会让 headers 和 {headers: headers} 或 es6 {headers}
      猜你喜欢
      • 2010-12-08
      • 1970-01-01
      • 2016-10-02
      • 2010-12-17
      • 2017-01-03
      • 2019-02-06
      • 2014-09-13
      • 2015-05-05
      • 2019-04-08
      相关资源
      最近更新 更多