【问题标题】:Calling REST api from angular2从 angular2 调用 REST api
【发布时间】:2016-12-12 12:30:02
【问题描述】:

我已经完成了 angular2 heroies 教程 https://angular.io/docs/ts/latest/tutorial/,现在我正在尝试调用我用 Node、Postgresql 和 Express 制作的 ral REST api。

调用 API 的 angular2 代码如下所示:

...

export class HeroService{

  private heroesUrl = 'http://192.168.4.13:3000/api/boxes'; //URL til api
  private headers = new Headers({'Content-Type': 'application/json'});
  constructor(private http: Http) {}

  getHeroes(): Promise<Hero[]> {
    return this.http.get(this.heroesUrl)
     .toPromise()
     .then(response => response.json().data as Hero[])
     .catch(this.handleError);
  }

...

浏览器控制台显示:

发生错误响应 {_body: Object, status: 404, ok: false, statusText: "Not Found", headers: Headers...} 例外:未捕获(承诺中):响应状态:404 Not Found for URL:null

Picture from REST API

我可以看到我的 API 没有被调用。 关于我错过了什么的任何想法?

最好的问候。

【问题讨论】:

  • 错误信息表明您输入了错误的 URL,即它返回 404。如果您还尝试在 response 上调用 .json(),那么它将失败,因为内容不是 JSON。您尝试调用的 API URL 是什么?您是如何在服务器端定义该 API 的?
  • 很遗憾,API 不公开,但我已经用图片更新了我的帖子,以便您可以从 API 中看到结果的结构。
  • 这可能很愚蠢,但是您是否尝试过从 URL 中删除 http:// 部分?此外,您能否打开浏览器控制台,选择网络选项卡并刷新您希望调用它的页面。这可能有助于更好地理解问题。
  • 然后它会导致 http 500: Uncaught (in promise): Response with status: 500 Internal Server Error for URL: null
  • 您能否发布浏览器控制台的图片 -> 选择此 API 调用的网络?另外,你是如何运行 angular2 服务器的?它是否由相同的后端提供服务,即它们是否具有相同的域?

标签: node.js rest angular


【解决方案1】:

我发现我需要删除这些行才能调用后端:

// Imports for faking the http service - in-memory web api
import { InMemoryWebApiModule }  from 'angular-in-memory-web-api';
import { InMemoryDataService }   from './in-memory-data.service';

我以为 Angular2 在不使用时会忽略它们,但导致新的后端 API 没有被调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-29
    相关资源
    最近更新 更多