HTTP拦截器使用Angular 4在失败的请求中获取状态0 [英] HTTP interceptor getting status 0 on failed request using Angular 4
问题描述
我有以下实施的HTTP拦截器 Angular ^ 4.3.6
。
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上阻止,但在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 OPTIONS http:// localhost:7001 / coreRobo / neuralProcess 404(未找到)
name:"HttpErrorResponse"
ok:false
status:0
statusText:"Unknown Error"
我不确定我在这里缺少什么,但我希望这个状态给我一些有效的东西404,403或者说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 ,请检查访问权限 - 服务器配置中的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.
value必须包含允许的来源列表。
The value must contain the list of allowed origins.
这篇关于HTTP拦截器使用Angular 4在失败的请求中获取状态0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!