Typescript / Angular2 http.post不设置标题

时间:2016-03-03 20:41:21

标签: typescript angular

我正试图从Angular2 beta 8发布json但是标题没有被传输:

import { RequestOptions, RequestMethod, RequestHeaders, RequestOptionsArgs, Http } from 'angular2/http';

// ...
let headers = new Headers(),
    body = JSON.stringify({ identifier, password });

headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');
let opts:RequestOptionsArgs = { headers: headers };

this.http.post(this.baseUrl + 'auth/login', body, opts)
    .subscribe(
         data => console.log(data),
         err => console.log(err.json().message),
         () => console.log('Authentication Complete')
    );

但Chrome中的XHR调用没有这些标头。 Chrome调试显示Content-Type标头已标记为Provisional Headers are Shown并显示Content-Type:text/plain;charset=UTF-8。标题值似乎是正确的:

console.log(headers.get('Content-Type')) // => 'application/json'
console.log(headers.get('Accept'))       // => 'application/json'

问题在于我正在进入RequestHeaders,但它应该只是Headers。为什么它没有给我一个错误,我不知道。

1 个答案:

答案 0 :(得分:14)

您需要像这样导入Headers类(从angular2/http导入时忘记了它):

import {
  RequestOptions,
  RequestMethod,
  RequestHeaders,
  RequestOptionsArgs,
  Http,
  Headers // <------
} from 'angular2/http';

// ...
let headers = new Headers(),
body = JSON.stringify({ identifier, password });

有关详细信息,请参阅此问题: