Angular: HttpGet 请求导致 HttpErrorResponse
Angular: HttpGet request leads to 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, …}
如果我通过邮递员尝试完全相同的 url 它会起作用并且我得到了我的结果。
有什么我遗漏的或错的吗?
我明白了。实际上我遇到了 2 个不同的问题:
- 我的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"
]
}
- 由于我的 api 通常需要很长时间(~3 分钟)才能回答我还需要为请求添加更长的超时时间:
this.http.get(url, { responseType: 'json', headers: new HttpHeaders({ timeout: '300000' }) })
我正在使用 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, …}
如果我通过邮递员尝试完全相同的 url 它会起作用并且我得到了我的结果。 有什么我遗漏的或错的吗?
我明白了。实际上我遇到了 2 个不同的问题:
- 我的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"
]
}
- 由于我的 api 通常需要很长时间(~3 分钟)才能回答我还需要为请求添加更长的超时时间:
this.http.get(url, { responseType: 'json', headers: new HttpHeaders({ timeout: '300000' }) })