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

时间:2017-05-16 16:27:16

标签: 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())    
}

当我在网络中检查时,我发现Content-Type被设置为text / plain,因此服务器没有接收任何数据。 任何建议将不胜感激。

5 个答案:

答案 0 :(得分:4)

更改_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())    
}

答案 1 :(得分:3)

试试这段代码:

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

答案 2 :(得分:2)

你应该使用这样的代码

async function whatever(y = "...") {
  await promise.using(getDatabaseConnection(), async conn => {
    try { // try/catch outside the using depending on whether the handling
          // requires the connection or not
      callAnotherFunction(await conn.query("some sql"), y); 
    } catch (e) {
      callAnotherFunction(e, y);
    }
  }); 
}

答案 3 :(得分:2)

引用Angular 2 Angular Http Guide @ angular / http已被弃用,@ angular / common / http应该是你在Angular 2 App中使用的那个。因为如果您没有指定http标头,则默认请求将作为Content-Type 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();

答案 4 :(得分:0)

2020年的Angular 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});
  }
}