在 Spring Boot 中实现跨域请求,您可以尝试以下几种方法:

  1. 使用 @CrossOrigin 注解:在您的 Controller 类或方法上使用 @CrossOrigin 注解,指定允许跨域的源地址、允许的请求方法、允许的请求头等信息。
@CrossOrigin(origins = 'http://example.com', methods = RequestMethod.GET)
@RestController
public class YourController {
    // Your methods here
}
  1. 配置 CorsFilter:创建一个实现了 javax.servlet.Filter 接口的 CorsFilter 类,并在配置中添加该过滤器。这种方法更为灵活,可以通过配置文件进行更多的自定义。
@Configuration
public class CorsConfig {
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOrigin('http://example.com');
        config.addAllowedMethod('*');
        config.addAllowedHeader('*');
        source.registerCorsConfiguration('/**', config);
        return new CorsFilter(source);
    }
}
  1. 全局配置跨域:在应用程序的主配置类(通常是带有 @SpringBootApplication 注解的类)中添加一个继承自 WebMvcConfigurerAdapter 的配置类,并覆盖 addCorsMappings 方法。
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping('/**')
                .allowedOrigins('http://example.com')
                .allowedMethods('*')
                .allowedHeaders('*');
    }
}

请确保已经按照上述方法进行配置,并且已重启应用程序以使配置生效。如果问题仍然存在,建议您检查请求是否正确发送,并确认服务器端是否正确处理了跨域请求。

SpringBoot 跨域请求配置详解及常见问题排查

原文地址: https://www.cveoy.top/t/topic/bG6Q 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录