Springboot 解决跨域问题 @杨章隐 - 简书

其实这里也没有什么技术含量,大概就是定义一个拦截器,然后直接控制转发就行了。
其中参数包括 跨域的域名 星号等于全部域名跨域
跨域的请求方式 "POST, GET, PATCH, DELETE, PUT"
跨域请求超时 3600


import org.springframework.context.annotation.Configuration;

import javax.servlet.*;

import javax.servlet.annotation.WebFilter;

import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebFilter(filterName = "CorsFilter ")

@Configuration

public class CorsFilter implements Filter {

    @Override

    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-Credentials", "true");

        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT");

        response.setHeader("Access-Control-Max-Age", "3600");

        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

        chain.doFilter(req, res);

    }

}

推荐阅读更多精彩内容