• springboot java 跨域 问题处理


    问题

    很多时候在控制器中设置了跨域注解 没有用!

    直接在拦截器中配置

    方式一

    @Component
    public class TokenInterceptor implements HandlerInterceptor {
    
    
    
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            System.out.println("进入LoginInterceptor拦截器---------------------------------------");
    
    
            //添加跨域CORS
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Headers", "X-Requested-With,content-type,token");
            response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH");
    }
    }
    
    

    方式二

    利用 CorsConfiguration 类解决

      /**
         * 配置跨域
         * @return
         */
        @Bean
        public CorsWebFilter corsFilter() {
            CorsConfiguration config = new CorsConfiguration();
            // cookie跨域
            config.setAllowCredentials(Boolean.TRUE);
            config.addAllowedMethod("*");
            config.addAllowedOrigin("*");
            config.addAllowedHeader("*");
            // 配置前端js允许访问的自定义响应头
            config.addExposedHeader("token");
            config.addExposedHeader("username");
            config.addExposedHeader("content-disposition");
            config.addExposedHeader("filename");
    
            UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
            source.registerCorsConfiguration("/**", config);
    
            return new CorsWebFilter(source);
        }
    
    
    
    

    ·

  • 相关阅读:
    中文简体汉字
    文件下载
    javaBean
    servlet和JSP笔记(EL表达式、javabean、jsp九大内置对象等)
    Http请求和响应
    Eclipse快捷键(可更新)
    反射笔记①
    泛型, 枚举,单例模式
    Ubuntu 14.04 安装 A卡HD7750 官方闭源 显卡驱动
    C语言--二维数组,字符串数组,多维数组
  • 原文地址:https://www.cnblogs.com/cfas/p/16142835.html
Copyright © 2020-2023  润新知