CORS跨域请求:前后端分离

2023-06-13,,

  1. 请求过滤器:

    /**
    *  OncePerRequestFilter保证在任何Servlet容器中都是一个请求只执行一次的过滤器。
    */
    public class CorsFilter extends OncePerRequestFilter {
    
    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse resp, FilterChain chain) throws ServletException, IOException {
    
        Properties props = PropertiesLoaderUtils.loadAllProperties("cors.properties");
        //允许的 客户端域名
        resp.addHeader("Access-Control-Allow-Origin", props.getProperty("cors.allowed-origins"));
        //允许的 方法名
        resp.addHeader("Access-Control-Allow-Methods", props.getProperty("cors.allowed-methods"));
        //允许服务端访问的客户端请求头,多个请求头用逗号分割,例如:Content-Type
        resp.addHeader("Access-Control-Allow-Headers", "Content-Type,X-Requested-With,token");
        //预检验请求时间
        resp.addHeader("Access-Control-Max-Age", props.getProperty("cors.max-age"));//30 min
        resp.addHeader("Access-Control-Allow-Credentials", "true");
    
        chain.doFilter(req, resp);
    }
    }

  2. web.xml中配置跨域过滤器:
    <!--配置跨域请求的过滤器-->
    <filter>
    <filter-name>cors</filter-name>
    <filter-class>com.jd.dashboard.cors.CrossFilter</filter-class>
    </filter>
    <filter-mapping>
    <filter-name>cors</filter-name>
    <url-pattern>/*</url-pattern>
    </filter-mapping>

  3. 过滤器中的属性配置如下:
#跨域请求CORS全局配置属性值

#允许访问的客户端域名,例如:http://web.xxx.com
cors.allowed-origins=http://front.xx.com

#允许访问的方法名
cors.allowed-methods=POST, GET, OPTIONS, DELETE

#允许服务端访问的客户端请求头,多个请求头用逗号分割,例如:Content-Type
cors.allowed-headers=Content-Type

#允许客户端访问的服务端响应头
cors.exposed-headers=

#是否允许请求带有验证信息,若要获取客户端域下的cookie时,需要将其设置为true
cors.allow-credentials=true

cors.max-age=1800

由于jsonp只支持GET方式的请求,所以这种方式比较推荐。

《CORS跨域请求:前后端分离.doc》

下载本文的Word格式文档,以方便收藏与打印。