• SpringBoot设置Access-Control-Allow-Origin跨域


    1、设置filter

    @Component
    @WebFilter(urlPatterns = "/*", filterName = "CorsFilter")
    public class CorsFilter implements Filter {
    
        @Override
        public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
            HttpServletResponse response = (HttpServletResponse) res;
            HttpServletRequest reqs = (HttpServletRequest) req;
            String curOrigin = reqs.getHeader("Origin");
            response.setHeader("Access-Control-Allow-Origin", curOrigin == null ? "true" : curOrigin);
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT");
            response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
            chain.doFilter(req, res);
        }
    
    
        @Override
        public void init(FilterConfig filterConfig) {
            System.out.println("=======================================================chulaile=================================================");
        }
    
        @Override
        public void destroy() {}
    
    }
    

    2 配置

    @Configuration
    public class CorsConfig  extends WebMvcConfigurerAdapter {
    
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**").allowedOrigins("*")
                    .allowedMethods("GET", "HEAD", "POST","PUT", "DELETE", "OPTIONS")
                    .allowCredentials(true).maxAge(3600);
        }
    
    }
    

    3

    @Configuration
    public class XXXXMvcConfigurer implements WebMvcConfigurer {
    
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("*")
                    .allowCredentials(true)
                    .allowedMethods("GET", "POST", "DELETE", "PUT","PATCH")
                    .maxAge(3600);
        }
    }
    

    4 @CrossOrigin
    原文链接:https://blog.csdn.net/qiuqiu1628480502/java/article/details/85289894

  • 相关阅读:
    如何在linux下使用sudo命令不用输入密码
    QT读写ini配置文件
    dubbo的灰度发布
    dubbo的重试原则
    dubbo的启动时检查
    dubbo的超时处理和配置覆盖
    dubbo配置文件加载顺序
    java基础-泛型的优点
    idea提交多个项目到github的同一个repository
    【掌握】dubbo环境搭建linux
  • 原文地址:https://www.cnblogs.com/leifonlyone/p/12844686.html
Copyright © 2020-2023  润新知