【发布时间】: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