English 中文(简体)
Cannot access server REST API from integrated browser using jquery
原标题:

I am having a Jersey REST Service application running on a server. This application should be accessed from a desktop application with an integrated browser, for which I can define HTML pages with Javascript. Thus, the client code is executed locally with the origin d://. When I am running my Jersey Application on my local computer with a localhost address, everything runs perfectly fine. However, when I deploy the Jersey application on the server and try to access it from my desktop application, an error is returned with the status 0. Using Postman on my local computer, I have no issue accessing the jersey appliation on the server. However, when I am checking my logs, I see, that no preflight request is sent via Postman (no request with origin != null).
Based on this problem I am guessing, that this is related to CORS. I added a CORS filter to my Jersey application but it is still not working. The server is not registering any incoming requests from my Desktop application. Has anybody an idea what I am missing? Thank you for the support.

My code for querying the data in the Desktop application:

var ajaxObj = {
        type: "POST", 
        url: jerseyApplicationUrl,
        crossDomain: true,
        data: JSON.stringify(inputFile),  
        contentType:"application/json",
        error: function(jqXHR, textStatus, errorThrown) {
            console.log("Error "+ textStatus +" " + jqXHR.getAllResponseHeaders() + " " + errorThrown+ " "+ jqXHR.status+" " +jqXHR.responseText);
        //Output: Error error 0 undefined
        },
        success: function(data) { 
                console.log("Server returns success for data query with result ");
        },
        complete: function(XMLHttpRequest) {
            //console.log( XMLHttpRequest.getAllResponseHeaders() );
        }, 
        dataType: "json" //request JSON 
    };
    $.ajax(ajaxObj);

My CORS class in the Jersey Application:
@Provider
@PreMatching
public class CorsFilter implements ContainerRequestFilter, ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext request) throws IOException {
    // If it s a preflight request, we abort the request with 
    // a 200 status, and the CORS headers are added in the
    // response filter method below.
    if (isPreflightRequest(request)) {
        request.abortWith(Response.ok().build());
        return;
    }
}

/**
 * A preflight request is an OPTIONS request
 * with an Origin header.
 */
private static boolean isPreflightRequest(ContainerRequestContext request) {
    return request.getHeaderString("Origin") != null
            && request.getMethod().equalsIgnoreCase("OPTIONS");
}

/**
 * Method for ContainerResponseFilter.
 */
@Override
public void filter(ContainerRequestContext request, ContainerResponseContext response)
        throws IOException {
    boolean debug = MtcServiceApplication.getInstance()!=null?MtcServiceApplication.getInstance().isDebug():false;
    // if there is no Origin header, then it is not a
    // cross origin request. We don t do anything.
    if (request.getHeaderString("Origin") == null) {
        return;
    }

    // If it is a preflight request, then we add all
    // the CORS headers here.
    if (isPreflightRequest(request)) {
        response.getHeaders().add("Access-Control-Allow-Credentials", "true");
        response.getHeaders().add("Access-Control-Allow-Methods",
            "GET, POST, PUT, DELETE, OPTIONS, HEAD");
        response.getHeaders().add("Access-Control-Allow-Headers",
            // Whatever other non-standard/safe headers (see list above) 
            // you want the client to be able to send to the server,
            // put it in this list. And remove the ones you don t want.
            "X-Requested-With, Authorization, " +
            "Accept-Version, Content-MD5, CSRF-Token, Content-Type");
    }
    
    // Cross origin requests can be either simple requests
    // or preflight request. We need to add this header
    // to both type of requests. Only preflight requests
    // need the previously added headers.
    response.getHeaders().add("Access-Control-Allow-Origin", "*");
}
}
问题回答

暂无回答




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签