http服务器如何响应404,在httpclient中检测来自服务器的http 404响应

博主在使用Angular的HTTP客户端进行API请求时遇到一个问题,当服务器返回404响应状态时,Angular客户端报告的状态代码却是0。在Chrome的网络标签中可以看到正确的404状态,但错误对象的status属性并未正确反映这一情况。代码示例展示了如何处理HTTP错误,但error.status始终未返回404。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我在从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。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值