我在从api检测404响应状态时遇到问题。如果您查看图像,您将看到chrome正确地记录了请求的404响应状态。问题是Angular的HTTP客户端报告的状态代码是“0”。我在这里做错什么了…?
代码:
checkNameTaken(clientId: string, name: string): Observable {
const baseUrl = this.configService.configBs.getValue().apiBaseUrl;
return this.http.get(`${baseUrl}/Rules/${clientId}/${name}`)
.pipe(
catchError( error => {
if ( !(error.error instanceof ErrorEvent)) {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
if (error.status === '404') {
return of(true);
}
console.error(
`Backend returned code ${error.status}, ` +
`body was: ${error.error}`);
}
return of(false);
}),
map(rule => rule ? true : false)
);
}
这是chrome的网络标签:
Request URL: http://localhost:57067/api/Rules/C7000050/tests
Request Method: GET
Status Code: 404 Not Found
Remote Address: [::1]:57067
Referrer Policy: no-referrer-when-downgrade
知道为什么当服务器返回404时error.status总是返回0吗?运行角度7.2.0
将代码更新为:
checkNameTaken(clientId: string, name: string): Observable {
const baseUrl = this.configService.configBs.getValue().apiBaseUrl;
return this.http.get(`${baseUrl}/Rules/${clientId}/${name}`)
.pipe(
catchError( error => {
if ( !(error.error instanceof ErrorEvent)) {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
if (error.status === 404) {
return of(true);
}
console.error(
`Backend returned code ${error.status}, ` +
`body was: ${error.error}`);
}
return of(false);
}),
map(rule => rule ? true : false)
);
}
当服务器返回404时,error.status始终为0。