【发布时间】:2021-04-03 15:35:25
【问题描述】:
我有一个 Angular 应用程序,它连接到我使用 jhipster 生成的 Spring Boot 应用程序。当我发送发布请求时,我收到此错误:
Access to XMLHttpRequest at 'http://localhost:8081/api/materials-add' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
-
我尝试在我的 Application.dev.yml 中激活 Cors,然后从 dev Profile 开始,但它不起作用。
-
我尝试将此方法放在我的配置类中:
@Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/api/**").allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"); }
但还是没有成功。
3.
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = jHipsterProperties.getCors();
if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) {
log.debug("Registering CORS filter");
source.registerCorsConfiguration("/api/**", config);
source.registerCorsConfiguration("/management/**", config);
source.registerCorsConfiguration("/v2/api-docs", config);
source.registerCorsConfiguration("http://localhost:4200/**",config);
}
return new CorsFilter(source);
}
这是一个已经存在的代码,我刚刚在最后一行添加了 localhost:4200。但仍然没有运气。有人可以帮助我或给我建议我接下来可以尝试什么吗?
Intellij 错误:
2020-12-25 20:17:47.229 WARN 38287 --- [ XNIO-1 task-3] o.z.problem.spring.common.AdviceTraits : Unauthorized: Full authentication is required to access this resource
2020-12-25 20:17:47.231 WARN 38287 --- [ XNIO-1 task-3] .m.m.a.ExceptionHandlerExceptionResolver : Resolved [org.springframework.security.authentication.InsufficientAuthenticationException: Full authentication is required to access this resource]
但是我通过我的网关登录授权并且我的网关和我的微服务都在同一个注册表中注册,所以我应该被授权是由于 CORS 导致的这个错误吗?
我刚刚在 application.dev.yml 中阅读了这部分内容: CORS 在微服务上默认禁用,因为您应该通过网关访问它们。
在我的网关中,我已经通过 application.dev.yml 允许了 cors,如下所示:
cors:
allowed-origins: '*'
allowed-methods: '*'
allowed-headers: '*'
exposed-headers: 'Authorization,Link,X-Total-Count'
allow-credentials: true
max-age: 1800
【问题讨论】:
标签: angular spring-boot cors jhipster