从获取请求 Angular 读取文本文件时出错

问题描述

我正在尝试使用 Angular Cli 11.0.6 从请求 GET 中读取文件中的内容,我使用此代码读取文件

 getFileText(url): Observable<any> {
  return this.http.get(url,{ responseType: 'text'})
  .pipe(
    retry(1),catchError(this.handleError)
  )
}

然后我运行“getFileText()”方法并将内容放入我的视图中:

  this.myServices.getFileText(this.url)
    .subscribe((data: any) => {
      this.txtcontent = data;
    });

当我从桌面浏览器看到它时,这很有效。但是当我从我的手机移动浏览器中使用相同的应用程序进行测试时,它不起作用,它显示错误

错误代码:0 消息:http://urlfile.example 的 Http 失败响应:0 未知错误

我尝试将 responseType 更改为 JSON 或 Blob,但它显示了同样的错误,有谁知道为什么会发生这种情况?谢谢。

解决方法

如果您的服务器和 Angular 应用都在 localhost 中运行,则可能是 CORS 源相关问题。

您可以参考这个链接:I get "Http failure response for (unknown url): 0 Unknown Error" instead of actual error message in Angular