SpringBoot中解决跨域问题

方法一:在需要的Controller类添加@CrossOrigin注解

@RequestMapping("/data")
@RestController
@CrossOrigin
public class DataController {
}

方法二:添加一个@Configuration类

@Configuration
public class CorsConfig {

    // 解决跨域问题
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*"); // 1
        corsConfiguration.addAllowedHeader("*"); // 2
        corsConfiguration.addAllowedMethod("*"); // 3
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig()); // 4
        return new CorsFilter(source);
    }
}

这个类的package必须跟Controller类在同一个package

你可能感兴趣的:(SpringBoot中解决跨域问题)