描述
目前应用开发前后端分离是大趋势,故而前后端部署在不同的两个域也是大概率事件,那么势必需要解决跨域请求的问题。
本文描述spring-boot项目中如何解决请求跨域的三种解决方案,以及升级spring-boot 2.4后的跨域问题。
解决
方案一
通过实现WebMvcConfigurer接口的addCorsMappings方法解决跨域问题。
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
// 所有的当前站点的请求地址,都支持跨域访问。
registry.addMapping("/**")
// 所有的外部域都可跨域访问
.allowedOrigins("*")
// 是否支持跨域用户凭证
.allowCredentials(true)
// 当前站点支持的跨域请求类型是什么
.allowedMethods("GET", "POST", "PUT", "DELETE")
.maxAge(3600);
}
}
方案二
使用@CrossOrigin注解实现跨域
@RestController
@CrossOrigin(origins = "*", maxAge = 3600)
public class TestController {
@GetMapping("/test")
public ApiResult<String> test() {
return null;
}
}
方案三
使用Filter实现跨域
@ConditionalOnProperty(name = "manage.api.cors", havingValue = "true")
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
注意
spring-boot升级到2.4版本以后,使用如下方案时会抛一下异常
java.lang.IllegalArgumentException: When allowCredentials is true, allowedOrigins cannot contain the special value "*" since that cannot be set on the "Access-Control-Allow-Origin" response header. To allow credentials to a set of origins, list them explicitly or consider using "allowedOriginPatterns" instead.
// 解决方法提示内容中也有香惜的说明
// 当allowCredentials设置为'true'时,allowedOrigins不能包含特殊值'*'
// 可以考虑使用allowedOriginPatterns代替