在Angular 2中使用CORS使用REST Api
我想使用在angular 2中另一台服务器上运行的RESTAPI 在“如何使用可观察对象”中:在Angular 2中使用CORS使用REST Api,angular,rest,typescript,Angular,Rest,Typescript,我想使用在angular 2中另一台服务器上运行的RESTAPI 在“如何使用可观察对象”中: import {Injectable} from 'angular2/core'; import {Http, Response} from 'angular2/http'; import {Hero} from './hero'; import {Observable} from 'rxjs/Observable'; @Injectable() export c
import {Injectable} from 'angular2/core';
import {Http, Response} from 'angular2/http';
import {Hero} from './hero';
import {Observable} from 'rxjs/Observable';
@Injectable()
export class HeroService {
constructor (private http: Http) {}
private _heroesUrl = 'http://someserver:8080/heroes'; // URL to external web api
getHeroes () {
return this.http.get(this._heroesUrl)
.map(res => <Hero[]> res.json().data)
.catch(this.handleError);
}
private handleError (error: Response) {
// in a real world app, we may send the error to some remote logging infrastructure
// instead of just logging it to the console
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}
}
显然,它不会得到任何数据。如何操作http头以便处理CORS请求
编辑1
- 我通过在后端相应地设置标题来修复CORS问题
- 我添加了地图和观测值的导入:
导入“rxjs/add/operator/map” 进口“rxjs/Rx”import {Injectable} from 'angular2/core'; import {Http, Response} from 'angular2/http'; import {Hero} from './hero'; import {Observable} from 'rxjs/Observable'; @Injectable() export class HeroService { constructor (private http: Http) {} private _heroesUrl = 'http://someserver:8080/heroes'; // URL to external web api getHeroes () { return this.http.get(this._heroesUrl) .map(res => <Hero[]> res.json().data) .catch(this.handleError); } private handleError (error: Response) { // in a real world app, we may send the error to some remote logging infrastructure // instead of just logging it to the console console.error(error); return Observable.throw(error.json().error || 'Server error'); } }
Uncaught (in promise) TypeError: object is not a constructor(…) [undefined:1]
当我在chrome开发控制台中单击异常以查看其来源时,它将打开一个新的空选项卡。。。现在有点卡在这里了在角度上与CORS无关。CORS纯粹是服务器浏览器。在网络控制台中检查您的请求是否真正执行,以及响应是什么。如果它被浏览器阻止。然后,您需要修改服务器以启用CORS支持。也许这有助于您通过在rest server@Gary谢谢,我不知道的情况下添加http头来处理CORS。我在nancyfx中添加了标题backend@AngelAngel谢谢,我添加了导入,现在有新的错误,请参阅我的edit@Ronin删除.catch()时会发生什么情况?尝试将catch与subscribe一起使用