【问题标题】:Consume REST Api using CORS in Angular 2在 Angular 2 中使用 CORS 使用 REST Api
【发布时间】:2016-03-12 23:02:56
【问题描述】:

我想使用 REST api,它在 Angular 2 的另一台服务器上运行。

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 请求?

编辑 1

  • 我通过在后端相应地设置标头解决了 CORS 问题。
  • 我添加了 map & observables 的导入:

    导入 'rxjs/add/operator/map' 导入'rxjs/Rx';

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

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

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

【问题讨论】:

  • CORS 可以通过在rest serverstackoverflow.com/questions/35957751/…添加http头来处理@
  • @Gary 谢谢,不知道。我在我的 nancyfx 后端添加了标题
  • @AngelAngel 谢谢,我添加了导入,现在出现新错误,请参阅我的编辑
  • @Ronin 删除 .catch() 会发生什么?尝试将 catch 与 subscribe 一起使用

标签: angular rest typescript


【解决方案1】:

在 Angular 中与 CORS 无关。 CORS 纯粹是服务器 浏览器的东西。如果您的请求真正执行,请检查网络控制台以及响应。如果被浏览器屏蔽。然后您需要修改服务器以启用 CORS 支持。

【讨论】:

    猜你喜欢
    • 2016-01-31
    • 2017-03-21
    • 2023-03-25
    • 2019-06-08
    • 2020-09-01
    • 2021-09-19
    • 1970-01-01
    • 2019-01-04
    • 2018-06-04
    相关资源
    最近更新 更多