全局允许跨域配置类
编写一个配置类即可
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class CommonIntercepter {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
//允许任何域名
corsConfiguration.addAllowedOrigin("*");
//允许任何头
corsConfiguration.addAllowedHeader("*");
//允许任何方法
corsConfiguration.addAllowedMethod("*");
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
//注册
source.registerCorsConfiguration("/**", buildConfig());
return new CorsFilter(source);
}
}
单个方法允许跨域
在需要跨域的方法上加注解 @CrossOrigin
@RestController
public class TestController {
@RequestMapping("/a")
//括号内参数为允许可访问的域列表 这里也可以配置通配符*
@CrossOrigin("http://localhost:8080")
public String t(){
return "helloworld";
}
}