以下是使用' toPromise'时出现的错误。在POST电话:
XMLHttpRequest无法加载http://jsonplaceholder.typicode.com/posts。 从' http://jsonplaceholder.typicode.com/posts'重定向至 ' https://captcha.gecirtnotification.com/pitc/?url=http%3a%2f%2fjsonplacehold ...212596678@ge.com& LANG = EN_US&安培; ZSQ = QZsC6JP75b8Z54VNTsJSKHnnWH0WsC6JPMpb6Vszsq' 已被CORS政策阻止:请求需要预检,即 不允许遵循跨源重定向。
我正在对jsonplaceholders模拟API(http://jsonplaceholder.typicode.com/)进行基本的POST调用。
使用' toPromise'时,我只会收到上述错误。实现。它在使用Observable时有效。我不确定承诺/可观察分辨率如何/为何影响实际的POST调用和/或预检调用。
这(使用toPromise)失败:
public testPostCall(): any {
let url = 'http://jsonplaceholder.typicode.com/posts';
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
let payload = {
"userId": 1,
"id": undefined,
"title": "Test API Title",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
};
return this.http.post(url, payload, options)
.toPromise()
.then((response: Response) => {
console.log('post response', response);
return response.json();
});
}
这(使用Observables)有效:
public testPostCall(): any {
let url = 'http://jsonplaceholder.typicode.com/posts';
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
let payload = {
"userId": 1,
"id": undefined,
"title": "Test API Title",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
};
return this.http.post(url, payload, options)
.map((response: Response) => {
console.log('post response', response);
return response.json();
})
.catch(this.handleError);
}
以下是导入:
import { Injectable } from '@angular/core';
import { Http, RequestOptionsArgs, Response, Headers, RequestOptions } from '@angular/http';
import { Observable, BehaviorSubject } from 'rxjs';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';