“Access-Control-Allow-Origin:*”对REST Web服务没有影响
我从JavaScript客户端(在机器A上运行)到Web服务器(在机器B上运行)进行AJAX调用。 客户端尝试访问由RESTful Web服务(Jersey)公开的URL,并且它被阻止并显示错误:
Access-Control-Allow-Origin不允许使用原始http:// localhost /
在服务器中,我添加了2个标头参数,允许访问任何客户端。 但它没有帮助:
@Context private HttpServletResponse servlerResponse; @POST @Path("testme") public void test(){ servlerResponse.addHeader("Access-Control-Allow-Origin", "*"); servlerResponse.addHeader("Access-Control-Allow-Credentials", "true"); }
对于JSP,相同的头文件有效:
test jsp test
我错过了什么吗?
谢谢
PS客户端部分是:
$.ajax({ type: "POST", url: "http://localhost:8080/login/testme", dataType: 'json', success: onLoginSuccess, error: onLoginError });
作为解决方案,我们实现了javax.servlet.Filter,它为每个响应添加了必需的标头:
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, java.io.IOException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) resp; // This should be added in response to both the preflight and the actual request response.addHeader("Access-Control-Allow-Origin", "*"); if ("OPTIONS".equalsIgnoreCase(request.getMethod())) { response.addHeader("Access-Control-Allow-Credentials", "true"); } chain.doFilter(req, resp); }
@epeleg这是我喜欢这样做的首选方式,即对响应进行过滤(Jersey 2.x):
@Provider public class CORSFilter implements ContainerResponseFilter { @Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { responseContext.getHeaders().add("Access-Control-Allow-Origin", "*"); } }