【问题标题】:Angular get data from API with path variable角度从 API 获取具有路径变量的数据
【发布时间】:2020-07-23 15:13:42
【问题描述】:

我对 Angular 比较陌生。我正在尝试从 API 获取数据。调用该 API,我必须将路径变量发送到该 API 以进行搜索。 Angular 是第 7 版。 Angular 项目在 localhost:4200 上运行,而返回 api 的项目在 localhost:8080 上运行。 我有许多其他来自 localhost:8080 的 API 正在运行。他们都工作。除了这个之外,其余的只是没有变量传递的 get 方法。 目前我正在本地设备上进行测试。 API的地址是

http://localhost8080/users/{pathVariable}

我尝试在 Postman 中使用 http://localhost/users/tester 进行测试,它可以工作,返回结果。

然后我尝试在 Angular 中使用该网址:

   const url='http://localhost:8080/users/testing';
   this.http.get<any>(url).subscribe(data => {this.rowData=data; });

我也尝试过使用变量:

    const test='testing';
    const url='http://localhost:8080/users/${test}';
    this.http.get<any>(url).subscribe(data => {this.rowData=data; });

但它根本不起作用。它总是显示错误,我没有返回任何数据。

我应该如何解决这个错误?

网络选项卡中的错误视图是这样的。

【问题讨论】:

  • 这个错误看起来更像是后端的错误。您是否尝试过使用假 api 并检查您是否能够获取数据。使用 Postman 再次检查您的 API
  • 是标题和邮递员一样。
  • 在使用邮递员进行测试时,我使用了相同的 url 'localhost:8080/users/testing' 并且它有效,我得到了返回数据。我复制了那个网址并尝试了角度,错误发生了。
  • 您是否在 Postman 中尝试过 http://localhost/users/tester url 或 http://localhost:8000/users/tester
  • angular 项目在 localhost:4200 上运行,返回 api 的项目在 localhost:8080 上运行。我也试过你说的。它在邮递员中不起作用。

标签: angular api


【解决方案1】:

更新

从日志看,您的服务器上似乎没有配置CORSPOSTMAN 起作用的事实是因为它不执行 CORS 策略,而 browsers 执行。您应该将以下标题添加到您的 public/index.php 或它所在的任何位置:

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, DELETE, OPTIONS');

* 基本上允许所有来源,而您可以将其替换为 origin /url

我相信你的路径中有一个错字。您已经在POSTMAN 上测试了users/tester,同时在代码中点击了users/testing。尝试解决这个问题:

 const url='http://localhost:8080/users/tester'; //<-- tester but rather testing
 this.http.get<any>(url).subscribe(data => {this.rowData=data; });

【讨论】:

  • 一开始我也是这么想的。所以,我从工作邮递员那里复制了 url 并粘贴到我的 angular 项目中。错误仍在发生。
  • @user8355629 发布来自网络标签的通话快照。
  • 请求 URL:localhost:8080/users/testing 推荐人策略:no-referrer-when-downgrade 内容长度:8 内容类型:application/json;charset=UTF-8 日期:星期四,2020 年 7 月 23 日 06 :26:12 GMT Accept: application/json, text/plain, / Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9 Connection: keep-alive主机:localhost:8080 来源:localhost:4200Referer:localhost:4200/querysearch Sec-Fetch-Dest:空 Sec-Fetch-Mode:cors Sec-Fetch-Site:same-site
  • 那行得通。非常感谢你。新的 api 位于项目的另一个文件中,该文件没有为 COR 配置。现在可以了。
  • 我在 API 生成项目中为 Angular 项目端口添加了 CORs 权限。 @CrossOrigin(origins = "localhost:4200", maxAge = 3600)。它现在工作正常。谢谢你。
猜你喜欢
  • 1970-01-01
  • 2017-09-22
  • 1970-01-01
  • 1970-01-01
  • 2019-10-07
  • 2018-03-28
  • 2019-02-08
  • 1970-01-01
  • 2021-03-31
相关资源
最近更新 更多