【问题标题】:Get HTTP response from server (localhost)从服务器(本地主机)获取 HTTP 响应
【发布时间】: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


【解决方案1】:

起初我的回答似乎无关紧要,但您需要能够看到您遇到了什么错误。您还应该在开发者控制台中,在请求的“网络”选项卡下确定 Http 错误代码是什么。

要在 Angular 中进行调用,您可以通过扩展以下行来获取更多信息:

 this.posts = this.http.get(this.ROOT_URL);

这使您几乎没有选择来显示和处理错误。相反,请尝试另一种形式:

this.http.get<PostStructure[]>(this.ROOT_URL).subscribe(
data => { 
          this.posts = [...data]; 
        }, 
err => { console.log(err); }, 
() => {}
);

然后您可以使用 err 变量来了解更多信息。

这里是 Angular Docs on Http 的链接,其中包括错误处理(其中有更好的示例说明如何处理):

https://angular.io/guide/http

同时查看您的浏览器控制台,您可能会收到评论所暗示的 CORS 错误。

【讨论】:

  • 有帖子描述了不推荐的代码示例。甚至还有一个 eslint 规则可以检测组件中的 subscribe 调用。帖子建议改用异步管道并将其组合起来,例如使用 catchError 运算符(如您已链接的文档中所述)。
  • @ChristophLütjen 同意,只是想让他收到错误消息并将他指向文档。
【解决方案2】:

在你的组件中

this.posts$ = this.http.get(this.ROOT_URL);

在你的 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多