其他分享
首页 > 其他分享> > springboot 实现允许跨域请求

springboot 实现允许跨域请求

作者:互联网

springboot mvc 项目可以用过WebMvcConfigurer接口然后重写addCorsMappings方法解决跨域,具体示例如下:

@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .maxAge(3600);
    }

}

springboot 前后端分离项目可以通过拦截器来实现允许跨域请求,具体代码示例如下:

@Configuration
public class CorsConfig {

    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(urlBasedCorsConfigurationSource);
    }

}

标签:请求,corsConfiguration,springboot,跨域,new,public,urlBasedCorsConfigurationSource
来源: https://blog.csdn.net/weixin_42280959/article/details/118445690