在Heroku上的Java JAX-RS API上启用CORS请求

时间:2019-02-14 07:40:07

标签: java heroku jax-rs

我有一个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的事,但我不确定。

将提供任何帮助。

1 个答案:

答案 0 :(得分:0)

使用常规过滤器:

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() {}
}