美文网首页
SpringBoot跨域请求

SpringBoot跨域请求

作者: jiahzhon | 来源:发表于2020-08-04 15:14 被阅读0次

    1、直接采用SpringBoot的注解@CrossOrigin
    Controller层在需要跨域的类或者方法上加上该注解即可

    2、处理跨域请求的Configuration

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

    3、采用过滤器的方式

     @Component
    public class CORSFilter implements Filter {
    
        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                throws IOException, ServletException {
            HttpServletResponse res = (HttpServletResponse) response;
            res.addHeader("Access-Control-Allow-Credentials", "true");
            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 {
        }
    }
    

    res.addHeader("Access-Control-Allow-Origin", "*")可用来设置白名单

    相关文章

      网友评论

          本文标题:SpringBoot跨域请求

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