Access to XMLHttpRequest at ‘http://localhost:8081/demo/test‘ from origin ‘null‘ has been blocked by

问题产生环境

前端发生异步请求访问后端数据时产生

后端:SpringBoot 项目

问题描述

Access to XMLHttpRequest at 'http://localhost:8081/demo/test' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. localhost:8081/demo/test:1 Failed to load resource: net::ERR_FAILED 
Access to XMLHttpRequest at ‘http://localhost:8081/demo/test‘ from origin ‘null‘ has been blocked by

问题原因

这是SpringBoot项目的跨域问题

解决办法

创建一个filter 解决即可

@Component public class SimpleCORSFilter implements Filter {      public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {         HttpServletResponse response = (HttpServletResponse) res;         response.setHeader("Access-Control-Allow-Origin", "*");         response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, HEAD");         response.setHeader("Access-Control-Max-Age", "3600");         response.setHeader("Access-Control-Allow-Headers", "access-control-allow-origin, authority, content-type, version-info, X-Requested-With");         chain.doFilter(req, res);     }     public void init(FilterConfig filterConfig) {     }     public void destroy() {     }  } 

请求成功
Access to XMLHttpRequest at ‘http://localhost:8081/demo/test‘ from origin ‘null‘ has been blocked by