我正在使用{N}+Angular 2。我正在对远程API进行Http POST调用。当我试图在App上运行API时,它返回一个状态为200但主体为空的响应。
但是,当我在POSTMAN上测试该API时,它给出了body。一旦我在postman上测试了API并在我的应用程序上运行它,它就会在响应中返回正文。请帮我弄清楚为什么会这样。
发布于 2017-03-10 01:06:50
Angular AJAX调用最初是可观察的。你有没有把你的可观察性变成一个承诺?
在Angular网站上通读本教程的这一部分应该会有所帮助,https://angular.io/docs/ts/latest/tutorial/toh-pt6.html
发布于 2017-03-10 01:35:39
下面是一个发出POST请求,然后通过订阅来处理响应的示例。
发布请求
MakePostRequest() {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http
.post('http://localhost:4200/api/end-point',
model,
{headers: headers})
.map((res: Response) => res.json())
.subscribe((res) => {
//do something with the response here
console.log(res);
});
}
}确保您添加的端口是正确的。如果您使用的是节点服务器,那么很可能端口应该与运行ng2应用程序的端口相同。但是,如果您使用的是PHP服务器,那么端口将是运行PHP服务器的任何端口。
所以在我的例子中,我的apache是在port 80上运行的。在这种情况下,我会将URL更改为以下内容,
.post('http://localhost:80/api/end-point',这是一个Get Request
Get请求
public GetRequest() {
let params: URLSearchParams = new URLSearchParams();
params.set('email', this.user.email);// set params to URL
params.set('api_key', this.apiKey); // set params to URL
return this.http.get('http://localhost:80/api/end-point',
{ search: params })
.map((res: Response) => res.json())
.subscribe((res) => {
console.log(res);
});
};还要确保您的组件中有正确的导入。
import {Http, Response, Headers, URLSearchParams} from '@angular/http';你听起来像是在一条道路上,这条路很快就会把你带到可观察到的地方。请记住,当您开始使用可观察性时,您将需要使用rxjs模块。在使用可观察数据时,您通常需要此导入,但从rxjs导入的数据要多得多。
import {Observable} from "rxjs";https://stackoverflow.com/questions/42701182
复制相似问题