Featured image of post Springboot解决跨域问题

Springboot解决跨域问题

image-20250406203609910

问题如图,命名前段发送的请求地址与方法都没问题,状态码也是200,但还是报错,得不到响应,这可能是跨域问题,比如我后端地址为8080,但前端是3006,就产生了跨域问题

解决方式

在后端项目创建一个文件,建议src/main/java/com/yourpackage/config/CorsConfig.java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
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("/**")
                .allowedOrigins("http://localhost:前端端口") // 前端地址
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedHeaders("*")
                .allowCredentials(true);
    }
}

将上述代码复制进入刚刚创建的文件中,如果像直接允许所有跨域访问可以用下面的代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
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("/**")  // 允许所有路径
                .allowedOrigins("*") // 允许所有来源(注意:不能和 allowCredentials 同时使用)
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .maxAge(3600);      // 预检请求缓存时间(秒)
    }
}
本站于2025年3月26日建立
使用 Hugo 构建
主题 StackJimmy 设计