public class CrosFilter implements Filter {
@Autowired
private AcmUtil acmUtil;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) response;
String allowedOrigins = acmUtil.getValue("allowedOrigins"); // 这里是动态从配置文件中读取的需要跨域的ip地址
if (StringUtils.isBlank(allowedOrigins)) {
allowedOrigins = "*";
}
res.setHeader("Access-Control-Allow-Origin", allowedOrigins);
res.setHeader("Access-Control-Allow-Headers",
"Content-Type,Content-Length, Authorization, Accept,X-Requested-With,token");
res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.setHeader("Access-Control-Allow-Credentials", "true");
res.setHeader("X-Powered-By", "Jetty");
filterChain.doFilter(request, response);
}
@Override
public void destroy() {
}
跨域错误信息:Access to XMLHttpRequest at 'http://192.168.0.120/auth/selectOrderCount' from origin 'http://192.168.0.124:8080' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'http://192.168.0.136:8080' that is not equal to the supplied origin.
1: 跨域看 from origin 'id地址' 和 Access-Control-Allow-Origin 中的ip地址是否一致
2: 可以使用注解的方式跨域,在需要跨域的controller类上加到@CrossOrigin(未测试过)
3: 如果前端传递token到后台,后台每次接收的token不一致需要在res.setHeader里面添加token字段即可
4: 跨域配置ip时需要加上端口号