在Spring Boot中全局启用CORS

我试图像这样在全球范围内启用CORS:

@Configuration

@ComponentScan("com.example")

@EnableWebMvc

public class OriginFilter extends WebMvcConfigurerAdapter {

@Override

public void addCorsMappings(CorsRegistry registry) {

registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE");

}

}

我也尝试过这种方法:

@Configuration

public class OriginFilter implements WebMvcConfigurer {

@Override

public void addCorsMappings(CorsRegistry registry) {

registry.addMapping("/**")

.allowedOrigins("*")

.allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD")

.allowCredentials(true);

}

}

但是这些都不对我有用。

可以@CrossOrigin为单个类添加注释,但是我想在全局范围内启用CORS。

回答:

您确实可以Filter按照答案中的定义定义自己的名称。Spring已经有了这样的功能CorsFilter,因此您不必自己创建一个。只需将其注册为bean,它就可以工作:

@Bean

public CorsFilter corsFilter() {

final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();

final CorsConfiguration config = new CorsConfiguration();

config.setAllowCredentials(true);

// Don't do this in production, use a proper list of allowed origins

config.setAllowedOrigins(Collections.singletonList("*"));

config.setAllowedHeaders(Arrays.asList("Origin", "Content-Type", "Accept"));

config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "OPTIONS", "DELETE", "PATCH"));

source.registerCorsConfiguration("/**", config);

return new CorsFilter(source);

}

以上是 在Spring Boot中全局启用CORS 的全部内容, 来源链接: utcz.com/qa/410982.html

回到顶部