美文网首页Spring-BootECMAScript
解决 spring boot 自定义过滤器跨域问题

解决 spring boot 自定义过滤器跨域问题

作者: 阿波罗程序猿 | 来源:发表于2018-05-14 15:28 被阅读17次
    使用自定义过滤器的时候

    使用自定义过滤器时,采用注解@CrossOrigin会失效,所以用以下代码来搞定

    public class TokenFilter extends OncePerRequestFilter {
        @Override
        protected void doFilterInternal(HttpServlet Requestrequest, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
            // do something
            cors(request, response);
            // do something
        }
      
        private void cors(HttpServletRequest request, HttpServletResponse response) {
            String allowOrigin = request.getHeader("Origin");
            String allowMethods = "GET,PUT, POST, DELETE";
            String allowHeaders = "Origin,No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified,Cache-Control, Expires, Content-Type, X-E4M-With";
            response.addHeader("Access-Control-Allow-Credentials", "true");
            response.addHeader("Access-Control-Allow-Headers", allowHeaders);
            response.addHeader("Access-Control-Allow-Methods", allowMethods);
            response.addHeader("Access-Control-Allow-Origin", allowOrigin);
        }
    }
    

    相关文章

      网友评论

        本文标题:解决 spring boot 自定义过滤器跨域问题

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