我正在使用{N} + Angular 2.我正在对远程API进行Http POST调用。当我尝试在应用程序上运行API时,它会返回状态为200但仍为空体的响应。
但是,当我在POSTMAN上测试API时,它会给出正文。一旦我在邮递员上测试API并在我的应用程序上运行它,它就会在响应中返回正文。请帮我弄清楚为什么会这样。
答案 0 :(得分:0)
Angular AJAX调用最初是Observables。你把Observable变成了承诺吗?
在Angular网站上阅读本教程的这一部分应该有所帮助,https://angular.io/docs/ts/latest/tutorial/toh-pt6.html
答案 1 :(得分:0)
这是一个发出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 app的端口相同。但是,如果您使用的是PHP服务器,则端口将是您运行的PHP服务器。
所以在我的情况下,我的apache
正在port 80
上运行。在这种情况下,我会将URL
更改为此,
.post('http://localhost:80/api/end-point',
这是Get Request
获取请求
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';
你听起来像是在走上一条将很快带给你观察的道路。请记住,当您开始使用observable时,您需要使用rxjs
模块。使用observable时,您通常需要进行此导入,但需要再次使用rxjs
。
import {Observable} from "rxjs";