新建一个Filter,核心代码如下: @Component @Order(Ordered.HIGHEST_PRECEDENCE) public class CorsFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { final HttpServletResponse rep = (HttpServletResponse) response; rep.addHeader("Access-Control-Allow-Origin", "*"); rep.addHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE"); rep.addHeader("Access-Control-Allow-Headers", "*"); rep.addHeader("Access-Control-Max-Age", "3600"); if("OPTIONS".equalsIgnoreCase(((HttpServletRequest)request).getMethod())){ rep.setStatus(HttpServletResponse.SC_OK); }else{ chain.doFilter(request,response); } } @Override public void destroy() { }
解决springboot 项目前端跨域问题
于 2019-07-12 14:47:25 首次发布