# Java CROS 跨域过滤器

📆 2021-12-16 18:33

# 跨域的定义

当浏览器发出请求时,目标地址的协议(protocol)、主机(host)、端口(port)任意一个不同就会现跨域问题。

# 解决方案

  • JSONP
  • CROS

# Java 实现

@Component
public class CrosFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest servletRequest=(HttpServletRequest) request;
        HttpServletResponse servletResponse=(HttpServletResponse) response;

        // 注意:一定要用 setHeader set

        // 是否接受该域名的请求
        servletResponse.setHeader("Access-Control-Allow-Origin", "*");

        // 是否允许携带Cookie
        servletResponse.setHeader("Access-Control-Allow-Credentials", "false");

        // 允许的方法
        servletResponse.setHeader("Access-Control-Allow-Methods", "POST,GET,PUT,OPTIONS,DELETE,PATCH");

        // 允许的Header
        servletResponse.setHeader("Access-Control-Allow-Headers", "origin,x-requested-with,content-type,accept,access_token");

        if(servletRequest.getMethod().equals(HttpMethod.OPTIONS.name())){
            servletResponse.setStatus(HttpStatus.SC_NO_CONTENT);
        }else{
            chain.doFilter(request, response);
        }
    }
}

# AXIOS

axios 会先发送一个 OPTIONS 的请求,OPTIONS 请求返回正确的 CROS Header 头后,可以解决跨域问题

最后更新于: 2/25/2022, 5:57:29 PM