Java spring boot添加配置文件,前端可访问,自定义跨源资源共享(CORS)设置,附源码

后端代码使用springboot框架开发的,使用postman测试接口可以正常使用,但是接口提供到前端是显示403 Forbidden报错的无法请求。

在后端代码中可以进行跨域配置,添加一个config文件即可

通过@Configuration注解来实现

java 复制代码
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("/**") // 对所有路径应用CORS配置
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true);
    }
}

方法说明:

  1. allowedOrigins(String... origins)‌:指定允许的源(域名)
  2. allowedOriginPatterns(String... patterns)‌(推荐):指定允许的源模式(支持通配符 *),Spring Boot 2.4+ 推荐此方式
  3. allowedMethods(String... methods)‌:指定允许的 HTTP 方法,例如 "GET", "POST", "PUT", "DELETE", "OPTIONS"等
  4. allowedHeaders(String... headers)‌:指定实际请求中允许的请求头字段,"*" 表示允许所有
  5. allowCredentials(boolean allow)‌:是否允许跨域请求携带凭证(Cookie、Authorization 等)。设为 true 时,allowedOrigins 不可为 "*" 。
  6. maxAge(long maxAge)‌:预检请求(OPTIONS)的缓存时间(单位:秒),减少重复预检次数 。