gpt4 book ai didi

angular - HTTP 拦截器使用 Angular 2、4、6、7、8、9 TypeScript 在请求失败时获取状态 0

转载 作者:搜寻专家 更新时间:2023-10-30 21:22:41 25 4
gpt4 key购买 nike

我使用 Angular ^4.3.6 实现了以下 HTTP 拦截器。

import {Injectable} from "@angular/core";
import {
HttpInterceptor,
HttpHandler,
HttpRequest,
HttpEvent,
HttpResponse,
HttpErrorResponse
} from "@angular/common/http";
import {Observable} from "rxjs/Observable";
import "rxjs/add/operator/do";

@Injectable()
export class InterceptorService implements HttpInterceptor {

intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
return next.handle(req).do(evt => {
console.log(evt);//this logs the success message properly
if (evt instanceof HttpResponse) {
//Keep going
}
},err => {
console.log(err);
//this logs the error but don't have useful info in it.
});

}
}

在成功的 http 调用中,我得到了 evt 的以下成员,这些成员在第一个 console.log 上有效。

ok:true
status:200
statusText:"OK"
type:4

]

但在失败时,我没有从第二个 console.log 的 err block 中获得正确的状态代码,但在 ZONE.js 的 DEV 控制台中有以下消息

zone.js:2263 OPTIONS http://localhost:7001/coreRobo/neuralProcess 404(Not Found)

name:"HttpErrorResponse"
ok:false
status:0
statusText:"Unknown Error"

我不确定我在这里遗漏了什么,但我希望该状态能给我一些有效的东西,比如 404,403 或 heck 500,当它显然是正在发生的事情时。

我只是想要这些值,以便我可以向 UI 显示正确的消息并帮助客户在失败时不会 panic 。

欢迎任何帮助。提前致谢。

最佳答案

如果您使用的是 CORS,则应在服务器配置中选中“Access-Control-Allow-Origin”。

我在我的 nginx 服务器上解决了这个问题,添加:

add_header "Access-Control-Allow-Origin" * always;

我错过了“always”参数,这导致了我和你一样的问题。

在我的示例中,您应该注意 header “*”的值。

该值必须包含允许的来源列表。

关于angular - HTTP 拦截器使用 Angular 2、4、6、7、8、9 TypeScript 在请求失败时获取状态 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47516465/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com