我正在尝试将请求从一个 localhost:4200(前面)发送到 localhost:xx(后面)。我在前端使用 Angular 8,在后端使用 .net core 2.2。
在后端启动时使用:
services.AddCors(options =>
{
options.AddPolicy("AllowAllOrigins",
builder =>
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials());
});
app.UseCors("AllowAllOrigins");
app.UseAuthentication();
app.UseMvc();
将身份验证与 jwt 集成并在拦截器中设置持有者和 token 的 Angular 时出现问题:
export class JwtInterceptor implements HttpInterceptor {
constructor(private authenticationService: AuthService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const currentUser = this.authenticationService.currentUserValue;
if (currentUser && currentUser.token) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${currentUser.token}`
}
});
}
return next.handle(request);
}
}
例如,向后端请求登录是可行的,但之后会出现错误:
Access to XMLHttpRequest at 'http://localhost:1190/api/messagemapping' from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.
问候并感谢您的帮助!
最佳答案
Anwers 已像@R 一样删除了AllowCredentials()。理查兹说!
关于angular - .net core 和 Angular 的预检响应中的 Access-Control-Allow-Headers 不允许请求 header 字段授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61923714/