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

标签 angular http typescript web-deployment angular-http-interceptors

我使用 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/

相关文章:

html - 如果数据库未返回 Angular 5 移动应用程序中特定标签的任何值,如何在 html 中隐藏标签?

javascript - 如何在外部使用 Angular 6 subscribe() 方法的结果?

http - 在主机 header 不匹配的虚拟主机环境中返回 400

typescript - '可观察<T >' is not a class derived from ' 可观察<T>'

reactjs - 重嵌套对象的 TypeScript 类型

javascript - 访问函数内的变量::TypeScript & Angular2

angular - 在 FormGroup 中更新 FormArray 时更改检测不起作用

autocomplete - Angular2,TypeError : el. toLowerCase 不是自动完成过程中的函数

php - 如何在没有 Content-Length header 的情况下流式传输 HTTP 文件上传?

javascript - 隐藏输入不会触发 React 的 onChange 事件