springboot如何解决跨域问题(4种方式)
Spring Boot 解决跨域问题的四种方式:
- 通过CorsFilter
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
- 通过配置文件
# application.yml
spring:
mvc:
cors:
allowed-origins: "*"
allowed-methods: "*"
- 通过@CrossOrigin注解
@CrossOrigin(origins = "*")
@RestController
public class MyController {
// ...
}
- 通过WebMvcConfigurer接口
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("*");
}
}
以上四种方式可以解决Spring Boot跨域问题,具体使用哪种取决于实际情况。
评论已关闭