我在从api检测404响应状态时遇到问题。如果查看图片,您会看到chrome在请求上正确记录了404响应状态。问题在于,Angular的http客户端报告状态代码为“ 0”。我在这里做错了什么...?
代码:
checkNameTaken(clientId: string, name: string): Observable<boolean> {
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吗?运行Angular 7.2.0
将代码更新为此:
checkNameTaken(clientId: string, name: string): Observable<boolean> {
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)
);
}
error.status在服务器返回404时始终始终为0。
答案 0 :(得分:1)
状态码是数字而不是字符串。
checkNameTaken(clientId: string, name: string): Observable<boolean> {
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)
);
}
如果不是这种情况,也许是这里提到的CORS问题:https://github.com/angular/angular/issues/20991