这是因为Angular的HttpClient默认使用了浏览器提供的XMLHttpRequest对象,在发送跨域请求时会先发送OPTIONS预检请求进行验证,此时如果代码中没有对OPTIONS请求进行处理,则会导致授权头被删除。解决方法是在服务端添加CORS(跨源资源共享)配置,或者在Angular代码中添加拦截器对OPTIONS请求进行处理,在请求头中添加Access-Control-Allow-Headers字段,并将其设为所需要的授权头。
以下是示例代码:
// 定义拦截器
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequestBearer ${localStorage.getItem('token')}
}
});
}
if (req.method === 'OPTIONS') {
req = req.clone({
headers: req.headers.set('Access-Control-Allow-Headers', 'Authorization')
});
}
return next.handle(req);
} }
// 在模块中添加拦截器 @NgModule({ imports: [ BrowserModule, HttpClientModule ], providers: [ { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true } ], bootstrap: [AppComponent] }) export class AppModule { }