Java跨域问题解决

定义跨域ip 域名

cors.addMapping=/**
cors.allowedOrigins=http://localhost,http://localhost:8080,https://www.baidu.com
cors.allowCredentials=true
cors.allowedMethods=GET,POST,PUT,DELETE,OPTIONS
cors.max_age=3600
  • 读取配置文件
  • @ConfigurationProperties(
        prefix = "cors"
    )
    public class CorsProperties {
        private String addMapping;
        private String[] allowedOrigins;
        private Boolean allowCredentials;
        private String[] allowedMethods;
        private Integer maxAge;
    }
    

  • 配置跨域
  • @Configuration
    @EnableConfigurationProperties({CorsProperties.class})
    public class CorsConfig implements WebMvcConfigurer {
        @Autowired
        private CorsProperties properties;
    
        public CorsConfig() {
        }
    
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping(this.properties.getAddMapping())
                    .allowedOrigins(this.properties.getAllowedOrigins())
                    .allowCredentials(this.properties.getAllowCredentials())
                    .allowedMethods(this.properties.getAllowedMethods())
                    .maxAge((long) this.properties.getMaxAge());
            
        }
    }
    

上一篇:springboot 后端解决跨域问题


下一篇:【koa2】使用token