首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Angular 6:无法正确设置http标头的Content-Type

Angular 6:无法正确设置http标头的Content-Type
EN

Stack Overflow用户
提问于 2018-12-05 01:57:43
回答 2查看 17.8K关注 0票数 7

我正在尝试使用angular 6中的HttpHeader进行post调用,并将Content-Type设置为应用程序/json。但是服务器得到的是x-www-form-urlencoded而不是Content-Type的application/json。

service.ts

代码语言:javascript
复制
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

代码语言:javascript
复制
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);
  })
}

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-12-05 02:09:06

您需要在option中设置headers。

代码语言:javascript
复制
return this.http.post(this.URL , body, {headers : new HttpHeaders({ 'Content-Type': 'application/json' })});
票数 12
EN

Stack Overflow用户

发布于 2018-12-05 02:27:47

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

试试这样的东西

代码语言:javascript
复制
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'});

希望它能帮上忙--快乐编码:)

票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53618872

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档