我在Angular 2中调用了一个http帖子.这在post man中工作得很好但是当我在Angular 2中实现这个API调用时,我得到No’Access-Control-Allow’错误.这是我的代码
@H_301_10@
CORS标题就像
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',headers) .map((res: Response) => { this.inspections = res.json(); return this.inspections; }) .catch(this.handleError); } else { //return cached data return this.createObservable(this.inspections); } }
headers.append('Access-Control-Allow-Origin','*');
需要由服务器提供.在客户端添加它们毫无意义.