【问题标题】:Typescript/Angular2 http.post doesn't set headersTypescript/Angular2 http.post 没有设置标题
【发布时间】:2016-06-17 09:28:44
【问题描述】:

我正在尝试从 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。为什么它没有给我一个错误,我不知道。

【问题讨论】:

标签: typescript angular


【解决方案1】:

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

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

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

查看这个问题了解更多详情:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-20
    • 1970-01-01
    • 2018-01-16
    • 1970-01-01
    • 2019-01-29
    相关资源
    最近更新 更多