Spring Boot 解决跨域问题的 5种方案
在Spring Boot中解决跨域问题,可以通过以下5种方案:
- 通过CorsFilter
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
- 通过@CrossOrigin注解
在Controller或者具体的方法上添加@CrossOrigin注解,例如:
@CrossOrigin(origins = "*")
@RestController
public class MyController {
// ...
}
或者
@RestController
public class MyController {
@CrossOrigin(origins = "*")
@RequestMapping("/my-endpoint")
public ResponseEntity<?> myEndpoint() {
// ...
}
}
- 通过WebMvcConfigurer
实现WebMvcConfigurer接口,并重写addCorsMappings方法,例如:
@Configuration
public class MyConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*");
}
}
- 通过配置文件
在application.properties或application.yml中添加以下配置:
# application.properties
spring.servlet.multipart.max-file-size=128KB
spring.servlet.multipart.max-request-size=128KB
spring.cors.allowed-origins=*
spring.cors.allowed-methods=GET,POST,PUT,DELETE
或者
# application.yml
spring:
cors:
allowed-origins: "*"
allowed-methods: "GET,POST,PUT,DELETE"
- 通过FilterRegistrationBean
注册一个CorsFilter的实例,例如:
@Bean
public FilterRegistrationBean<CorsFilter> simpleCorsFilter() {
评论已关闭