,所以我正在使用httpclient.get()进行休息调用。我已经设置了API以返回时间504。
查看Google DevTools时,我可以看到调用是呼叫,状态为504。但是,当我调试代码时,我得到的httperrorresponse我获得的状态为0。
我还设置了API以返回400响应,当我调试该代码时,响应状态为400。为什么400个传播,但没有504?
?我们使用的是Angular 6.0.6
更好的方法是实现错误处理程序。就我而言,我有一个通用类来拨打HTTP呼叫,所有服务(例如:eSublyService,供应商服务等)将与COOMMA API通信以进行REST API呼叫。以下是处理错误的示例代码。如果HTTP状态代码为404。
,这就是您将看到的服务器端错误 - 代码:404 消息:http http://localhost:5000/apiv1/account:404找不到
这是我的常见服务看起来。
@Injectable({
providedIn: 'root'
})
export class ApiService {
getUrlvalue: string;
constructor(private http: HttpClient) { }
private formatErrors(error: any) {
let errorMessage = '';
if (error.error instanceof ErrorEvent) {
errorMessage=`Client side Error: ${error.error.message}`;
} else {
errorMessage=`Server side Error - Code: ${error.status}nMessage: ${error.message}`;
}
console.log(errorMessage);
return throwError(error.error);
}
get(path: string, params: HttpParams = new HttpParams()): Observable<any> {
//console.log(`${environment.api_url}${path}`);
this.getUrlvalue = `${environment.api_url}${path}`;
console.log('API service get request is making to : ' + this.getUrlvalue);
return this.http.get(this.getUrlvalue, { params }) //, { params }
.pipe(
catchError(this.formatErrors)
);
}
put(path: string, body: Object = {}): Observable<any> {
console.log(`${environment.api_url}${path}`);
return this.http.put(
`${environment.api_url}${path}`,
JSON.stringify(body), httpHeaderOptions
).pipe(catchError(this.formatErrors));
}
post(path: string, body: Object = {}): Observable<any> {
console.log(`${environment.api_url}${path}`);
return this.http.post(
`${environment.api_url}${path}`,
JSON.stringify(body), httpHeaderOptions
).pipe(catchError(this.formatErrors));
}
delete(path): Observable<any> {
console.log(`${environment.api_url}${path}`);
return this.http.delete(
`${environment.api_url}${path}`
).pipe(catchError(this.formatErrors));
}
}
从其他服务链接帐户服务中,这就是简单http get
的呼吁。
@Injectable({
providedIn: 'root'
})
export class AccountService {
// private http: HttpClient
constructor(private apiService: ApiService) { }
getAccounts(): Observable<Deal[]> {
return this.apiService.get('/account')
.pipe(
tap(deals => console.log('fetched Accounts 111111')),
catchError(this.handleError('getAccounts', []))
);
}
事实证明我们的API网关未正确设置,我们没有返回正确的标题。
'Access-Control-Allow-Methods': 'POST,GET,OPTIONS',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token',