解决Angular中CORS请求失败时读取响应的方法可以通过使用HttpClient拦截器来实现。以下是一个示例代码:
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
@Injectable()
export class CorsInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler) {
return next.handle(req).pipe(
catchError((error: HttpErrorResponse) => {
// Check if it's a CORS error
if (error.error instanceof ErrorEvent && error.error.type === 'CORS') {
// Read the response body
const errorMessage = `CORS Error: ${error.error.message}`;
// Do something with the error message
console.error(errorMessage);
}
return throwError(error);
})
);
}
}
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { AppComponent } from './app.component';
import { CorsInterceptor } from './cors.interceptor';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, HttpClientModule],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: CorsInterceptor,
multi: true,
},
],
bootstrap: [AppComponent],
})
export class AppModule {}
现在,当发生CORS错误时,CorsInterceptor将拦截错误并读取响应体,并将错误消息打印到控制台中。您可以根据需要进行处理,例如显示错误消息给用户或执行其他操作。