首页 文章

在Angular 2中使用CORS消耗REST Api

提问于
浏览
1

我想使用在角度2的另一台服务器上运行的REST api .

documentation they provide an example如何使用observables:

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');
  }
}

请注意,我刚刚更改了 _heroesUrl 以便使用外部api,其余部分与文档中完全相同 .

不幸的是它会给我一个错误:

EXCEPTION: TypeError: this.http.get(...).map is not a function in [null]

显然它不会获得任何数据 . 如何操作http标头以便处理CORS请求?

Edit 1

  • 我通过在后端相应地设置 Headers 来修复CORS问题 .

  • 我添加了map&observables的导入:

import'rxjs / add / operator / map'import'rxjs / Rx';

现在前一个错误消失了,但是在我的控制台中弹出了一个新错误:

Uncaught (in promise) TypeError: object is not a constructor(…) [undefined:1]

当我点击异常以查看它在chrome dev控制台中的来源时,它会打开一个新的空标签...现在卡在这里

1 回答

  • 2

    与Angular中的CORS无关 . CORS纯粹是服务器< - >浏览器的东西 . 如果您请求真正执行以及响应,请检入网络控制台 . 如果它被浏览器阻止 . 然后,您将需要修改服务器以启用CORS支持 .

相关问题