Spring-boot2.0 先后端分离项目 跨域问题

将Spring-boot 从1.5.x升级到2.0后,浏览器出现跨域问题:java

Failed to load http://192.168.1.123:8080/mypath: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://192.168.1.123:8080' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

缘由:Spring-boot2.0后 allowCredentials为falsegit

解决方式:github

1.全局设置:spring

@Configuration
@EnableWebMvc
public class CorsConfig implements WebMvcConfigurer {
 
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        //设置容许跨域的路径
        registry.addMapping("/**")
                //设置容许跨域请求的域名
                .allowedOrigins("*")
                //这里:是否容许证书 再也不默认开启
                .allowCredentials(true)
                //设置容许的方法
                .allowedMethods("*")
                //跨域容许时间
                .maxAge(3600);
    }

注意:corsconfig 实现方法也不同,1.5.x WebMvcConfigurerAdapter 在2.0中改接口已被弃用,使用新的接口WebMvcConfigurer跨域

二、局部使用注解@CrossOrigin 在Controller 或者方法上设置(全局的配置 在@CrossOrigin里依旧可用)浏览器

参考:https://github.com/spring-projects/spring-boot/issues/12488app

相关文章
相关标签/搜索