美文网首页
Spring Boot跨域配置

Spring Boot跨域配置

作者: 鳌拜的弟弟熬夜 | 来源:发表于2023-08-26 19:49 被阅读0次

    import org.springframework.context.annotation.Bean;

    import org.springframework.context.annotation.Configuration;

    import org.springframework.web.cors.CorsConfiguration;

    import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

    import org.springframework.web.filter.CorsFilter;

    /**

    * Cross-domain configuration

    */

    @Configuration

    public class CrosConfig {

        // Sets sources that are allowed across domains

        private static String[]originsVal =new String[] {

            "*"

        };

        /**

         * Cross domain filter

         *

         * @return

         */

        @Bean

        public CorsFiltercorsFilter() {

            UrlBasedCorsConfigurationSource source =new UrlBasedCorsConfigurationSource();

            CorsConfiguration corsConfiguration =new CorsConfiguration();

            this.addAllowedOrigins(corsConfiguration);

            corsConfiguration.addAllowedHeader("*");

            corsConfiguration.addAllowedMethod("*");

            corsConfiguration.addAllowedOrigin("*");

            source.registerCorsConfiguration("/**",corsConfiguration);

            return new CorsFilter(source);

        }

        private void addAllowedOrigins(CorsConfiguration corsConfiguration) {

            for(String origin:originsVal) {

                    corsConfiguration.addAllowedOrigin("http://" + origin);

                    corsConfiguration.addAllowedOrigin("https://" + origin);

             }

         }

    }

    相关文章

      网友评论

          本文标题:Spring Boot跨域配置

          本文链接:https://www.haomeiwen.com/subject/zqjimdtx.html