【发布时间】:2021-10-17 11:14:35
【问题描述】:
我正在处理一个 Angular 项目,我想在其中从服务器数据库获取 HTTP 响应。 到目前为止我所拥有的:当我通过 Visual Studio 2019 运行项目时,连接到 Microsoft SQL 数据库并在浏览器中成功响应。
这是我调用时得到的 JSON 数据 https://localhost:44311/api/ExampleTable1
[
{
"firstClm": "bob1 ",
"secondClm": "1"
},
{
"firstClm": "bob10 ",
"secondClm": "10"
},...]
在我的 app.component.html 我有:
<button igxButton igxRipple='red' class="text-white" (click)='getPosts()'>
<span class="text-white"> Get JSON </span>
</button>
<div *ngFor="let post of posts | async">
{{ post | json }}
</div>
在 app.components.ts 我有:
export class AppComponent {
// readonly ROOT_URL = "https://jsonplaceholder.typicode.com/posts";
readonly ROOT_URL = "https://localhost:44311/api/ExampleTable1";
posts: any;
constructor(private http: HttpClient) { }
getPosts() {
this.posts= this.http.get(this.ROOT_URL);
}
}
当我将https://jsonplaceholder.typicode.com/posts 作为 ROOT_URL 时,一切正常,并且我可以看到 JSON 数据,但如果我使用 https://localhost:44311/api/ExampleTable1 作为 ROOT_URL,则没有任何反应。如果我通过浏览器去https://localhost:44311/api/ExampleTable1,可以看到JSON数据。
为什么我无法从本地主机获取 JSON 数据?
附:我正在使用 C# 和 Visual Studio 2019。
【问题讨论】:
-
检查浏览器控制台,您一定遇到了 CORS 错误。
-
正如@AakashGarg 所写,请。检查浏览器 > 开发人员工具 > 网络并发布您看到的错误或添加 rxjs 错误处理并发布您在 rxjs 错误分支中获得的错误。
标签: c# angular database server httpclient