HTTP拦截器使用Angular 2,4,6,7,8,9 TypeScript在失败的请求上获取状态0 [英] HTTP interceptor getting status 0 on failed request using Angular 2,4,6,7,8,9 TypeScript
问题描述
我使用Angular ^4.3.6
具有以下HTTP拦截器的实现.
I have following implementation of HTTP interceptors with Angular ^4.3.6
.
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上有效.
On the successful http call, I get following members of evt
which are valid on the first console.log.
ok:true
status:200
statusText:"OK"
type:4
]
但是如果失败,我在第二个console.log的err
块中没有正确的状态代码,但是在ZONE.js的DEV控制台中有以下消息
But on failure I don't have proper status code from the err
block on the second console.log but have following message in DEV console from ZONE.js
zone.js:2263选项 http://localhost:7001/coreRobo/neuralProcess 404(找不到)
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.
I am not sure what I am missing here but I wanted that status to give me something valid like 404,403 or heck 500 when it clearly is that what is happening.
我只是想要这些值,以便可以向UI显示正确的消息,并帮助客户端避免因失败而惊慌.
I just wanted those values so that I can show proper message to the UI and help client not panic on failure.
欢迎任何帮助.预先感谢.
Any help is welcomed. Thanks in advance.
推荐答案
如果您使用的是 CORS ,则应在您的计算机中选中" Access-Control-Allow-Origin "服务器配置.
If You are using CORS you should check "Access-Control-Allow-Origin" in your server configuration.
我在 nginx 服务器上解决了此问题,
I Solved this on my nginx server adding:
add_header "Access-Control-Allow-Origin" * always;
我错过了"总是"参数,该参数给我带来了与您相同的问题.
I missed the "always" parameter which caused me the same problem as yours.
在我的示例中,您应注意标题"*"的值.
You should pay attention to the value of the header "*" in my example.
该值必须包含允许的来源列表.
The value must contain the list of allowed origins.
这篇关于HTTP拦截器使用Angular 2,4,6,7,8,9 TypeScript在失败的请求上获取状态0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!