【问题标题】:Angular 2 - Receiving a POST Response Header with Content-Length > 0 but no contentAngular 2 - 接收 Content-Length > 0 但没有内容的 POST 响应标头
【发布时间】:2016-04-12 23:17:33
【问题描述】:

在 Angular 2 中,我使用 Http.post() 来检索一些 JSON 数据。当我使用 cURL 或 HttpRequestor 时,一切正常。但是,使用 Angular,我得到了一个 Content-Length > 0 的响应标头,但响应本身没有数据。

public retrieveJsonData() {
    var url = 'https://somewhere.com/whatever/GetItem?token=XXXX&resource=YYYY&data=%7B%22id%22%3A2207%7D';
    let options = new RequestOptions({});

    return this.http
        .post(url, '', options)
        .map(result => result.json())
        .catch(this.handleError);
}

请求标头:

POST /whatever/GetItem?token=XXXX&resource=YYYY&data=%7B%22id%22%3A2207%7D HTTP/1.1
Host: somewhere.com
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:45.0) Gecko/20100101 Firefox/45.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Referer: http://localhost:8888/
Content-Length: 0
Content-Type: text/plain;charset=UTF-8
Origin: http://localhost:8888
Connection: keep-alive

响应标头:

HTTP/1.1 200 OK
Date: Tue, 12 Apr 2016 22:49:23 GMT
Server: Apache/2.2.15 (CentOS) mod_ssl/2.2.15 OpenSSL/1.0.1e-fips
Set-Cookie: Foo=6djdhg7pnsqavk0nqa83u7rqt6; path=/; secure
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Content-Length: 1311
Keep-Alive: timeout=15, max=1000
Connection: Keep-Alive
Content-Type: text/json

所以在这个例子中 Content-Length = 1311 但响应是空的。如果我使用 HttpRequester 之类的工具,则 POST 会按预期工作,并且响应为 1311 个字符。怎么回事?

【问题讨论】:

  • 您可以在您的浏览器开发工具(如firebug)中看到响应正文,如果响应正确,则表示您的代码有错误。看起来您想使用 GET,但当前方法是 POST。
  • 上面的请求和响应头是直接从 Firebug 复制的。此调用需要 POST 请求,并且可以在 Angular 2 以外的环境中正常工作。

标签: angular http-post angular2-services


【解决方案1】:

这是我发布请求的方式

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

        this.http.post(url, JSON.stringify({firstName:'Joe',lastName:'Smith'}),{headers:headers})
            .map((res: Response) => res.json())
            .subscribe((res:Person) => this.postResponse = res);

用你的值替换后试试这个。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-16
    • 1970-01-01
    • 1970-01-01
    • 2011-11-06
    • 2020-07-15
    • 2022-01-09
    • 2015-12-13
    • 2013-04-06
    相关资源
    最近更新 更多