在Spring Boot中,可以通过配置跨域来允许不同源的请求访问后端接口。下面是一种常见的跨域配置方式:

  1. 创建一个配置类(例如CorsConfig):
@Configuration
public class CorsConfig {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedOrigins("*")
                        .allowedMethods("GET", "POST", "PUT", "DELETE")
                        .allowedHeaders("*")
                        .allowCredentials(true)
                        .maxAge(3600);
            }
        };
    }
}
  1. 在addCorsMappings方法中,使用CorsRegistry来配置跨域规则。上述示例中的配置允许所有来源(allowedOrigins(""))的请求访问后端接口,允许的请求方法包括GET、POST、PUT和DELETE(allowedMethods("GET", "POST", "PUT", "DELETE")),允许的请求头部包括所有(allowedHeaders("")),允许携带cookie(allowCredentials(true)),并设置预检请求的缓存时间为3600秒(maxAge(3600))。

  2. 在以上配置中,跨域请求的URL模式为"/",即所有URL都会被允许跨域访问。如果只想允许特定的URL跨域访问,可以使用其他URL模式,例如"/api/"。

  3. 将CorsConfig配置类添加到Spring Boot应用的主类上,例如:

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
    
    @Bean
    public CorsConfig corsConfig() {
        return new CorsConfig();
    }
}

通过以上配置,Spring Boot应用就可以支持跨域访问了

springboot如何进行跨域配置

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

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