SpringBoot-跨域访问
方法一:
单个接口实现跨域
在controller 方法上加 @CrossOrigin 注解
方法二
全局跨域处理
自定义 WebMvcConfigurer 注册到容器里,可以执行访问的路径
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration(proxyBeanMethods = false)
public class MyCorsConfiguration {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**");
}
};
}
}
方法三:
Spring Security 中配置跨域
@Bean
protected CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("*"));
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "HEAD", "OPTION", "PUT", "DELETE"));
configuration.setAllowedHeaders(Arrays.asList("*"));
// CORS 会有一个预检的OPTION请求,设置maxAge将预检命令进行缓存,而不是每次都执行预检请求
configuration.setMaxAge(3600L);
configuration.addExposedHeader("Authorization");
configuration.addExposedHeader("UUID");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}