【发布时间】:2016-12-24 10:33:27
【问题描述】:
我在 Angular 2 中调用 http 帖子。这在 post man 中运行良好,但是当我在 Angular 2 中实现此 API 调用时,我得到 No 'Access-Control-Allow' 错误。这是我的代码
getInspections(): Observable<IInspection[]> {
if (!this.inspections) {
let body =JSON.stringify({"Statuses":["Submitted", "Opened"]});
let headers = new Headers({ 'Content-Type': 'application/json' });
headers.append('Access-Control-Allow-Origin','*');
let options = new RequestOptions({ headers: headers });
return this.http.post(this._baseUrl + '/api/Inspect/ListI',body,options)
.map((res: Response) => {
this.inspections = res.json();
return this.inspections;
})
.catch(this.handleError);
}
else {
//return cached data
return this.createObservable(this.inspections);
}
}
或者我可以这样做吗?只需传递标题而不是选项
getInspections(): Observable<IInspection[]> {
if (!this.inspections) {
let body =JSON.stringify({"Statuses":["Submitted", "Opened"]});
let headers = new Headers({ 'Content-Type': 'application/json' });
//headers.append('Access-Control-Allow-Origin','*');
// let options = new RequestOptions({ headers:headers });
return this.http.post(this._baseUrl + '/api/Inspect/ListI',body,headers)
.map((res: Response) => {
this.inspections = res.json();
return this.inspections;
})
.catch(this.handleError);
}
else {
//return cached data
return this.createObservable(this.inspections);
}
}
【问题讨论】:
-
您可以直接传递标头(我猜它需要是像
{headers}这样的对象(虽然不确定)但这与您的 CORS 错误完全无关。
标签: rest angular cors angular2-http