【发布时间】:2019-07-25 22:27:36
【问题描述】:
我在从 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)
);
}
当服务器返回 404 时,error.status 仍然始终为 0。
【问题讨论】:
-
Propbaly 因为状态码是
int而不是string。试试:error.status === 404 -
if (error.status === '404')您正在将数字与字符串进行比较。关于错误代码零:您有两种类型的404:第一种是您到达服务器但找不到资源,第二种是您无法到达服务器。在这里,您可能到达了服务器,但忘记添加错误代码。 -
可能您忘记在可以重现问题的地方添加 stackblitz... 寻求调试帮助的问题(“为什么此代码不起作用?”)必须包含所需的行为,a具体问题或错误以及在问题本身中重现它所需的最短代码。没有明确问题陈述的问题对其他读者没有用处
-
@trichetriche 我对有时 404 的返回 0 感到迷茫。你能提供更多信息吗?
-
@smnbbrv 我不确定如何为此发布 plunkr,因为它仅在服务器返回 404 状态代码时才会专门复制。我还需要将我的 api 部署到面向互联网的某个地方,而我在这里做不到。
标签: angular angular-http