Angular:HttpGet 请求导致 HttpErrorResponse

问题描述

我正在使用 Angular 创建一个 Web 应用程序,我想使用 get 发送一个 HttpRequest 以从我的 api 服务器接收数据。

这是我的 http get 数据客户端:

import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class DataService {

  constructor(private http: HttpClient) { }

  getData(url: string): Observable<any> {
    console.log("getting data from API with url: " + url);
    return this.http.get(url,{ responseType: 'json' });
  }
}

我通过按钮点击调用它:

this.dataService.getData(requestString).subscribe(
      (data: any) => {
        console.log(data);
      });

当我尝试它时收到错误消息:

ERROR HttpErrorResponse {headers: HttpHeaders,status: 0,statusText: 'UnkNown Error',url: '...',ok: false,…}

如果我通过邮递员尝试完全相同的网址,它会起作用并且我得到我的结果。 有什么我遗漏的或错误的吗?

解决方法

我想通了。实际上我有两个不同的问题:

  1. 我的 launch.json 是错误的。自从我在 chrome 上启动以来,我需要“--disable-web-security”运行时参数:
     {
              "type": "chrome","request": "launch","name": "Launch Chrome against localhost","url": "http://localhost:4200","webRoot": "${workspaceFolder}","runtimeArgs": [
                "--disable-web-security"
              ]
        }
  1. 由于我的 api 通常需要很长时间(约 3 分钟)来回答我还需要为请求添加更长的超时时间:
    this.http.get(url,{ responseType: 'json',headers: new HttpHeaders({ timeout: '300000' }) })

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...