如何在angular2中将头设置为application/json

如何在angular2中将头设置为application/json,angular,typescript,post,header,Angular,Typescript,Post,Header,我试图用Angular2发送HTTP post请求,但无法将头设置为内容类型应用程序JSON 我的代码是: login(url,postdata) { var headers = new Headers({'Content-Type': 'application/json'}); return this._http.post(url,JSON.stringify(postdata),this.headers) .map(res => res.json())

我试图用Angular2发送HTTP post请求,但无法将头设置为内容类型应用程序JSON

我的代码是:

login(url,postdata)
{
    var headers = new Headers({'Content-Type': 'application/json'});
    return this._http.post(url,JSON.stringify(postdata),this.headers)
    .map(res => res.json())    
}
当我在网络中检查时,我发现内容类型设置为text/plain,所以服务器并没有接收任何数据。
如有任何建议,将不胜感激。

更改
\u http.post
参数:

login(url,postdata) {
    var headers = new Headers({'Content-Type': 'application/json'});
    return this._http.post(url,postdata,{headers:headers})
                .map(res => res.json())    
}

您应该使用这样的代码

let headers = new Headers();
headers.append('Content-Type', 'application/json');

let options = new RequestOptions({ headers: headers });
return this.http.post(url, JSON.stringify(postdata), options).map(res => res.json());
请尝试以下代码:

private _getHeaders():Headers {
   let header = new Headers({
     'Content-Type': 'application/json'
   });

   return header;
}



public login(url, postdata){
   let options = new RequestOptions({
      headers: this._getHeaders()
   });
   return this.http.post(url, JSON.stringify(postdata),options).map(res => res.json());
}
引用Angular 2@Angular/http已被弃用,并且@Angular/common/http应该是您在Angular 2应用程序中使用的。因为如果不指定http头,默认请求将作为内容类型text/plain发送,因此修改http头的方法如下:

import { HttpClient, HttpHeaders } from '@angular/common/http';
.....
const req = this.http.post('/api/PostRequest/',
                            JSON.stringify(object),
                            {
                             headers:new HttpHeaders()
                             .set('Content-Type','application/json')
                             }).subscribe();

2020年第9版

export class ApiService {

  private headers = new HttpHeaders({
    'Content-Type': 'application/json',
  });

  constructor(
    private http: HttpClient) {
  }

  get(path: string, params: HttpParams = new HttpParams()): Observable<any> {
    return this.http.get(`${environment.apiUrl}${path}`, {params, headers: this.headers});
  }
}
导出类API服务{
私有标头=新的HttpHeader({
“内容类型”:“应用程序/json”,
});
建造师(
专用http:HttpClient){
}
获取(路径:string,参数:HttpParams=newhttpparams()):可观察{
返回this.http.get(`${environment.apirl}${path}`,{params,headers:this.headers});
}
}

Join聊天也有一些类似的问题……仍然无法设置标题。实际上,在向服务器发送post请求时,负载没有被发送。我检查了网络中的内容类型及其文本/plain,而不是application/json。Accept:application/json,text/plain,/Accept编码:gzip,deflate,br Accept语言:en-US,en;q=0.8连接:保持活动内容长度:35内容类型:文本/普通