zoukankan      html  css  js  c++  java
  • springBoot解决跨域问题

    Springboot跨域问题三种解决方案

    1.自定义跨域过滤器

    编写过滤器

    public class MyCorsFilter implements Filter {
    
        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
            HttpServletResponse res = (HttpServletResponse) response;
            //是否允许后续请求携带认证信息(cookies),该值只能是true,否则不返回
            res.addHeader("Access-Control-Allow-Credentials", "true");
            //指定允许其他域名访问
            // 一般用法(*,指定域,动态设置),3是因为*不允许携带认证头和cookies
            res.addHeader("Access-Control-Allow-Origin", "*");
            //该次请求的请求方式
            res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
            //该次请求的自定义请求头字段
            res.addHeader("Access-Control-Allow-Headers", "Content-Type,X-CAF-Authorization-Token,sessionToken,X-TOKEN");
            if (((HttpServletRequest) request).getMethod().equals("OPTIONS")) {
                response.getWriter().println("ok");
                return;
            }
            chain.doFilter(request, response);
        }
    
        @Override
        public void destroy() {
        }
    
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
        }
        
    }

    注册过滤器

    /**
         * 注册自定义跨域过滤器
         */
        @Bean
        public FilterRegistrationBean registerFilter(){
            FilterRegistrationBean bean = new FilterRegistrationBean();
            bean.addUrlPatterns("/*");
            bean.setFilter(new MyCorsFilter());
            return bean;
        }

    2.针对单个接口,使用注解@CrossOrigin

    @CrossOrigin
    @RequestMapping("customAnalysisConfig")
    @RestController
    public class CustomAnalysisConfigController {
    }

    3.基于WebMvcConfigurerAdapter配置加入Cors的跨域

    @Configuration
    public class CorsConfig implements WebMvcConfigurer {
    
        /**
         * 跨域支持
         */
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("*")
                    .allowCredentials(true)
                    .allowedMethods("GET", "POST", "DELETE", "PUT")
                    .maxAge(3600);
        }
    }
  • 相关阅读:
    普通文本输入数学符号的方式
    Chrome crx离线插件下载及安装
    Solidworks常见问题一览
    数学学术资源站点(zz)
    最难读的20个英文单词
    运用html5 canvas做飞机大战游戏(2)
    html
    运用html5 canvas做飞机大战游戏(1)
    js
    css
  • 原文地址:https://www.cnblogs.com/lusaisai/p/13329951.html
Copyright © 2011-2022 走看看