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

我有以下 HTTP 拦截器的实现 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 有效。

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

]

但是在失败时,我没有从第二个 console.log 的 err 块中获得正确的状态代码,但是在 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 显示正确的消息并帮助客户在失败时不会恐慌。

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

如果您正在使用 CORS,您应该检查服务器配置中的“Access-Control-Allow-Origin”。

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

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

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

你要注意我例子中header“*”的值

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

我找到了导致问题的原因。这是一个服务器端问题。您需要先设置 CORS 中间件,然后再设置剩余的 API 个中间件。

请注意我正在使用 Laravel 5.6 + Angular 5

密码错误

'api' => [
            'throttle:60,1',
            'bindings',
            \Barryvdh\Cors\HandleCors::class,
        ],

当前代码

'api' => [
            \Barryvdh\Cors\HandleCors::class,
            'throttle:60,1',
            'bindings'
        ],

在Asp.net核心API我解决这个问题的方法是在UseAuthentication和UseAuthorization之前写"UseCors",主要是当认证服务在CORS服务之前,当认证服务直接返回时,它没有为它设置 CORS header。