前后端分离项目,跨域问题

跨域问题

当一个资源去访问另一个不同域名或者同域名不同端口的资源时,就会发出跨域请求。如果此时另一个资源不允许其进行跨域资源访问,那么访问就会遇到跨域问题。
springboot项目默认不允许处理跨域请求,前端报错:has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

解决方法

1.添加注解

在启动类上添加 @CrossOrigin

2.添加WebMvcConfigurer配置类

WebMvcConfigurer是web自动配置类在web启动时自动加载的一个类。

@Configuration(
    proxyBeanMethods = false
)
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
    private final WebMvcConfigurerComposite configurers = new WebMvcConfigurerComposite();

    public DelegatingWebMvcConfiguration() {
    }

    @Autowired(
        required = false
    )
    public void setConfigurers(List<WebMvcConfigurer> configurers) {
        if (!CollectionUtils.isEmpty(configurers)) {
            this.configurers.addWebMvcConfigurers(configurers);
        }
    }

其中WebMvcConfigurerComposite是WebMvcConfigurer的子类,setConfigurers将所有WebMvcConfigurer类加载进ioc,用以配置底层
所以利用WebMvcConfigurer可以将允许跨域逻辑添加到springboot中

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 设置允许跨域的路径
        registry.addMapping("/**")
                // 设置允许跨域请求的域名
                .allowedOriginPatterns("*")
                // 是否允许cookie
                .allowCredentials(true)
                // 设置允许的请求方式
                .allowedMethods("GET", "POST", "DELETE", "PUT")
                // 设置允许的header属性
                .allowedHeaders("*")
                // 跨域允许时间
                .maxAge(3600);
    }
}
posted @ 2023-10-09 20:55  新游  阅读(33)  评论(0)    收藏  举报