springboot+mybatis框架搭建--4.跨域配置

现在基本都谈前后端分离,为了支持跨域,只要加一个Filter即可实现:

    @Component
    @Slf4j
    public class CorsFilter implements Filter {
    
        @Override
        public void doFilter(ServletRequest req, ServletResponse resp,
                             FilterChain chain) throws IOException, ServletException {
                HttpServletResponse res = (HttpServletResponse) resp;
    
                // 这里最好不要写通配符,如果允许多个域请求数据的话,可以直接用逗号隔开:"http://www.baidu.com,http://google.com"  
                  
                res.setHeader("Access-Control-Allow-Origin", "*");  
                  
                res.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
                  
                res.setHeader("Access-Control-Allow-Headers", "Authorization,DNT,User-Agent,Keep-Alive,Content-Type,accept,origin,X-Requested-With");
                  
                res.setHeader("Access-Control-Allow-Credentials","true");
    
                res.addHeader("Access-Control-Max-Age","18000");
    
                res.addHeader("Access-Control-Expose-Headers","Content-Type,Access-Control-Allow-Origin,Access-Control-Allow-Headers,Access-Control-Request-Method,X-Requested-With,accept,Origin,Authorization");
                  
                chain.doFilter(req, resp);  
                  
                }
        @Override
        public void init(FilterConfig filterConfig) {}
        @Override
        public void destroy() {}
    }

添加这个Filter后,浏览器得到的返回数据:


springboot+mybatis框架搭建--4.跨域配置_第1张图片
image.png

你可能感兴趣的:(springboot+mybatis框架搭建--4.跨域配置)