问题描述
我正在使用 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,…}
如果我通过邮递员尝试完全相同的网址,它会起作用并且我得到我的结果。 有什么我遗漏的或错误的吗?
解决方法
我想通了。实际上我有两个不同的问题:
- 我的 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' }) })