Spring Boot全局跨域配置

1、问题: 在前后端分离的环境下进行项目开发,前台通过url请求后台的接口时,需要进行跨域,如果后台项目有很多Controller控制器,需要在每个Controller控制器的类上都添加@CrossOrigin跨域注解,这样就会显得重复。在Spring Boot项目中,可以配置全局跨域。

2、解决方法: 创建一个跨域的配置类CorsConfig.java,然后通过@Configuration注解将该类交给Spring容器进行管理和生效。

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CorsConfig implements WebMvcConfigurer {
          
   
    @Override
    public void addCorsMappings(CorsRegistry registry) {
          
   
        registry.addMapping("/**")  // 匹配了所有的URL
                .allowedHeaders("*")  // 允许跨域请求包含任意的头信息
                .allowedMethods("*")  // 设置允许的方法
                .allowedOrigins("*")  // 设置允许跨域请求的域名
                .allowCredentials(true);  // 是否允许证书,默认false
    }
}
经验分享 程序员 微信小程序 职场和发展