我想允许跨源请求到我的服务器。我找到了以下过滤器代码:
public class CorsFilter implements Filter {
// For security reasons set this regex to an appropriate value
// example: ".*example\\.com"
private static final String ALLOWED_DOMAINS_REGEXP = ".*";
public void doFilter(ServletRequest servletRequest,
ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) servletRequest;
HttpServletResponse resp = (HttpServletResponse) servletResponse;
String origin = req.getHeader("Origin");
if (origin != null && origin.matches(ALLOWED_DOMAINS_REGEXP)) {
System.out.println("CorsFilter:: origin matches, yey");
resp.addHeader("Access-Control-Allow-Origin", origin);
if ("options".equalsIgnoreCase(req.getMethod())) {
resp.setHeader("Allow", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS");
if (origin != null) {
String headers = req.getHeader("Access-Control-Request-Headers");
String method = req.getHeader("Access-Control-Request-Method");
resp.addHeader("Access-Control-Allow-Methods", method);
resp.addHeader("Access-Control-Allow-Headers", headers);
resp.setContentType("text/plain");
}
resp.getWriter().flush();
return;
}
}
// Fix ios6 caching post requests
if ("post".equalsIgnoreCase(req.getMethod())) {
resp.addHeader("Cache-Control", "no-cache");
}
if (filterChain != null) {
filterChain.doFilter(req, resp);
}
}
@Override public void destroy() {}
@Override public void init(FilterConfig arg0) throws ServletException {}
}
似乎只有在首先有一个 OPTIONS 请求时它才会做任何事情。但是,就我而言,我没有看到任何 OPTIONS 请求,而只有一个 GET 请求。我错过了什么吗?解决办法是什么?