在@Configuration注解下的类中添加如下配置
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/some-controller-you-want-to-CORS").allowedOrigins("http://your.front.end.domain.name:your-port");
}
};
}
例如:
@SpringBootApplication
@Configuration
public class CrowdsourcingExampleBackEndApplication {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(CrowdsourcingExampleBackEndApplication.class);
app.setWebApplicationType(WebApplicationType.SERVLET);
app.run(args);
}
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("http://localhost:8080");
}
};
}
}