美文网首页
SpringBoot允许跨域无效原因

SpringBoot允许跨域无效原因

作者: 林万程 | 来源:发表于2020-05-12 14:15 被阅读0次

    关键F12看浏览器日志有没有Response to preflight request doesn't pass access control check,没有就说明访问路径错了

    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.cors.CorsConfiguration;
    import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
    import org.springframework.web.filter.CorsFilter;
    
    /**
     * 允许跨域
     * 解决浏览器端如下报错:
     * <br>Access to XMLHttpRequest at 'http://localhost:8081/Ass/login'
     * <br>from origin 'http://localhost:8080' has been blocked by CORS policy:
     * <br>Response to preflight request doesn't pass access control check:
     * <br>No 'Access-Control-Allow-Origin' header is present on the requested resource.
     * <p>CORS支持跨域配置不生效且报的比上面的少了一行是因为路径错误(例如下面的少了Ass)
     * <br>Access to XMLHttpRequest at 'http://localhost:8081/list'
     * <br>from origin 'http://localhost:8080' has been blocked by CORS policy:
     * <br>No 'Access-Control-Allow-Origin' header is present on the requested resource.
     */
    @Configuration
    public class CorsConfig {
        @Bean
        public CorsFilter corsFilter() {
            final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            final CorsConfiguration configuration = new CorsConfiguration();
            // 是否允许请求带有验证信息
            configuration.setAllowCredentials(true);
            // 允许访问的客户端域名
            configuration.addAllowedOrigin("*");
            // 允许服务端访问的客户端请求头
            configuration.addAllowedHeader("*");
            // 允许访问的方法名,GET POST等
            configuration.addAllowedMethod("*");
            source.registerCorsConfiguration("/**", configuration);
            return new CorsFilter(source);
        }
    }
    
      // 携带 cookie 以便 session 生效
      axios.defaults.withCredentials=true;
    

    相关文章

      网友评论

          本文标题:SpringBoot允许跨域无效原因

          本文链接:https://www.haomeiwen.com/subject/tnhbnhtx.html