lili lili - 5 months ago 32x
Javascript Question

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

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

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

private HttpServletResponse servlerResponse;

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");
<head><title>test jsp</title></head>

Am I missing something?


P.S the client part is:

type: "POST",
url: "http://localhost:8080/login/testme",
dataType: 'json',
success: onLoginSuccess,
error: onLoginError


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, {
    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);