“Access-Control-Allow-Origin:*” has no influence in REST Web Service

此生再无相见时 提交于 2019-12-07 03:09:55

问题


I make an AJAX call from JavaScript client (running on machine A) to Web server (running on machine B). Client tries to access a URL exposed by RESTful Web service (Jersey), and it is blocked with error:

Origin http://localhost/ is not allowed by Access-Control-Allow-Origin

In server I added 2 header parameters that allow access to any client. However it didn't help:

@Context
private HttpServletResponse servlerResponse;

@POST
@Path("testme")
public void test(){
    servlerResponse.addHeader("Access-Control-Allow-Origin", "*");
    servlerResponse.addHeader("Access-Control-Allow-Credentials", "true");
}

The same headers work in case of JSP:

<%
    response.addHeader("Access-Control-Allow-Origin", "*");
    response.addHeader("Access-Control-Allow-Credentials", "true");
%>
<html>
<head><title>test jsp</title></head>
<body>
test
</body>
</html>

Am I missing something?

thanks

P.S the client part is:

$.ajax({
    type: "POST",
    url: "http://localhost:8080/login/testme",
    dataType: 'json',
    success: onLoginSuccess,
    error: onLoginError
});

回答1:


As a solution, we implemented javax.servlet.Filter that adds required headers to every response:

    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);
}



回答2:


@epeleg This is my preferred way of doing things like this is to do filtering of response (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", "*");
    }
}


来源:https://stackoverflow.com/questions/5406350/access-control-allow-origin-has-no-influence-in-rest-web-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!