美文网首页
SpringBoot-跨域问题处理

SpringBoot-跨域问题处理

作者: 流年逝去sky | 来源:发表于2021-08-28 21:36 被阅读0次

    方式一:在Controller中添加注解:
    @CrossOrigin(allowCredentials = "true",originPatterns = "*")


    image.png

    方式二:通过@Configuration配置并注入Filter方式,开放允许的域名

    package com.example.springboot3;
    
    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;
    
    @Configuration
    public class CorsConfig {
        @Bean
        public CorsFilter corsFilter() {
            UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            CorsConfiguration corsConfiguration = new CorsConfiguration();
            corsConfiguration.setAllowCredentials(true);
            corsConfiguration.addAllowedOriginPattern("http://localhost:9001");
            corsConfiguration.addAllowedHeader("*");
            corsConfiguration.addAllowedMethod("*");
            source.registerCorsConfiguration("/**", corsConfiguration);
            return new CorsFilter(source);
        }
    }
    
    

    相关文章

      网友评论

          本文标题:SpringBoot-跨域问题处理

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