angular - 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; });
但它根本不起作用。它总是显示错误,我没有返回任何数据。
我应该如何解决这个错误?
解决方案
更新
从日志看来,您CORS
的服务器上似乎没有配置。工作的事实POSTMAN
是因为它不执行CORS
策略而browsers
执行。您应该将以下标题添加到您的public/index.php
或它所在的任何地方:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, DELETE, OPTIONS');
*
基本上允许每个来源,而您可以将其替换为origin /url
您的来源。
老的
我相信你的路径中有一个错字。您已经在输入代码时测试了users/tester
on 。尝试修复:POSTMAN
users/testing
const url='http://localhost:8080/users/tester'; //<-- tester but rather testing
this.http.get<any>(url).subscribe(data => {this.rowData=data; });
推荐阅读
- html - 粘性列 - 相同 CSS 上的不同字体/粗体
- azure-devops - 如何通过 Rest API 将主题专家发布到 Azure DevOps
- python - AttributeError 'str' 对象没有属性 'keys'
- python - 多个列表到行和列
- apostrophe-cms - 管理模式关闭时调用 jquery 文档准备就绪
- javascript - 地球轨道模拟速度不正确
- java - 移动文件的java静态方法中的多线程?
- devexpress - 行号未正确对齐
- javascript - 在两个元素悬停时显示内容
- java - 错误:java:包 org.springframework.boot.loader 不存在