首页 > 解决方案 > Angular 使用路径变量从 API 获取数据

问题描述

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

http://localhost8080/users/{pathVariable}

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

然后我尝试在 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; });

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

错误

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

网络选项卡中的错误视图是这样的。 在此处输入图像描述

标签: angularapi

解决方案


更新

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

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

*基本上允许每个来源,而您可以将其替换为origin /url您的来源。

老的

我相信你的路径中有一个错字。您已经在输入代码时测试了users/testeron 。尝试修复:POSTMANusers/testing

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

推荐阅读