SpringBoot全局跨域配置

通过实现 WebMvcConfigurer ,推荐,不能配置多个,只能配置一个

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.example;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedHeaders("*")
.allowedMethods("*");
}
}

通过过滤器配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@Configuration
public class CorsConfig {
@Bean
CorsWebFilter corsWebFilter(){
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
// 允许所有请求头
config.addAllowedHeader("*");
// 允许所有方式
config.addAllowedMethod("*");
// 允许所有来源
config.addAllowedOrigin("*");
// 允许附带cookie信息
config.setAllowCredentials(true);

// 适用于所有请求
source.registerCorsConfiguration("/**", config);
return new CorsWebFilter(source);
}
}