我有一个Java Web应用程序,我从jQuery向使用JAX-RS配置的Rest API发送一些请求,在我的本地计算机上它运行正常,但在Heroku上部署之后,它给了我一个错误
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at...
特别是,我正在从jQuery向此端点发送POST请求。
我已经为我的应用程序配置了CORS过滤器,这导致它在我的本地计算机上运行(在此之前,应用程序在我的本地计算机上给了我相同的错误)。无论如何,这是我如何配置它
@Provider
public class CORSFilter implements ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {
responseContext.getHeaders().add("Access-Control-Allow-Origin", "*");
responseContext.getHeaders().add("Access-Control-Allow-Headers",
"Location, origin, content-type, accept, authorization, enctype, content-disposition");
responseContext.getHeaders().add("Access-Control-Expose-Headers", "Location");
responseContext.getHeaders().add("Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS, HEAD");
}
}
我还尝试将这些标头添加到我回馈的Response对象作为对请求的响应,但没有运气。
我相信它必须是一些Heroku的东西,但我不确定。
任何帮助,将不胜感激。
使用普通过滤器:
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
public class CORSFilter implements Filter {
private static final String ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin";
private static final String ACCESS_CONTROL_ALLOW_METHODS = "Access-Control-Allow-Methods";
private static final String ACCESS_CONTROL_ALLOW_HEADERS = "Access-Control-Allow-Headers";
private static final String ACCESS_CONTROL_EXPOSE_HEADERS = "Access-Control-Expose-Headers";
private static final String ALL = "*";
private static final String ALLOWED_METHODS = "GET";
private static final String ALLOWED_HEADERS =
"origin, content-type, accept, Authorization, x-requested-with";
private static final String EXPOSE_HEADERS = "TEST";
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse sresponse = (HttpServletResponse) response;
sresponse.setHeader(ACCESS_CONTROL_ALLOW_ORIGIN, ALL);
sresponse.setHeader(ACCESS_CONTROL_ALLOW_METHODS, ALLOWED_METHODS);
sresponse.setHeader(ACCESS_CONTROL_ALLOW_HEADERS, ALLOWED_HEADERS);
sresponse.setHeader(ACCESS_CONTROL_EXPOSE_HEADERS, EXPOSE_HEADERS);
chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) {}
public void destroy() {}
}