Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invoke REST Webservice from the javascript by Preflight Request?

I am trying to invoke the service which was in another domain from the javascript itself. I could able to request the cross domain service . But I cant retrieve the information from the service. Some how I have been blocked by the same origin policy. Please help me to find the errors in the code.

My Client side Javascript Code :

var requestJsonData;

function crossDomainCall(){  ** It will be called by button click **
    requestJsonData = createCORSRequest('POST', 'IPAddress/servicePath');
    if (requestJsonData){
        requestJsonData.onreadystatechange = handler;
        requestJsonData.send();
    }
    else {
        alert('Cross Domain Call is not invoked');
    }
}

function handler(evtXHR) {
    if(requestJsonData.readyState   ==  4) {
        if(requestJsonData.status   ==  200) {
            var response    =   requestJsonData.responseText;
        }
        else {
            alert(" Invocation Errors Occured " + requestJsonData.readyState + " and the status is " + requestJsonData.status);
        }
    }
    else {
        alert("currently the application is at " + requestJsonData.readyState);
    }
}
function createCORSRequest(method, url){
    var xhr;
        xhr = new XMLHttpRequest();
    if ("withCredentials" in xhr){
        xhr.open(method, url, true);
        xhr.setRequestHeader('X-PINGOTHER', 'pingpong');
    } else if (typeof XDomainRequest != "undefined"){
        xhr = new XDomainRequest();
        xhr.open(method, url);
    } else {
        xhr = null;
    }
    return xhr;
}

Service code :

@OPTIONS
@Path("/servicePath")
@Produces("*/*")
@Consumes("*/*")
public Response corsRequest() {
    Response response   =   null;
    ResponseBuilder builder =   null;
    builder =   Response.ok();
    builder.header("Access-Control-Allow-Headers", "X-PINGOTHER");
    builder.header("Access-Control-Max-Age","1728000");
    builder.header("Access-Control-Allow-Origin","Origin_Ip_Address");
    builder.header("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
    builder.header("Content-Type","text/plain");
    builder.header("Connection", "Keep-Alive");
    response    =   builder.build();
    System.out.println("Exited from Options method");
    return response;
}

@POST
@Path("/servicePath")
@Produces("application/json")
public String drawRegions() {
    System.out.println("Entered inside Post method");
            // Some calculation to arrive jsonObject.
    return jsonObject;
}

From the code, I have received the following as a results.

OPTIONS Method Request and Response Headers

Request Headers :

OPTIONS /SolartisGeoCodeLookUpService/Service/drawRegions HTTP/1.1

Host: Cross_Domain_IP_Address

User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:25.0) Gecko/20100101 Firefox/25.0

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8

Accept-Language: en-US,en;q=0.5

Accept-Encoding: gzip, deflate

Origin: Origin_IP_Address

Access-Control-Request-Method: POST

Access-Control-Request-Headers: x-pingother

Connection: keep-alive

Pragma: no-cache

Cache-Control: no-cache

Response Headers

HTTP/1.1 200 OK

Server: Apache-Coyote/1.1

Access-Control-Allow-Headers: X-PINGOTHER

Connection: Keep-Alive

access-control-allow-origin: Origin_IP_Address

Access-Control-Max-Age: 1728000

Access-Control-Allow-Methods: POST, GET, OPTIONS

Content-Type: text/plain

Content-Length: 0

Date: Thu, 12 Dec 2013 12:39:27 GMT

Response Cache Header

Response Headers From Cache

Access-Control-Allow-Head... X-PINGOTHER Access-Control-Allow-Meth... POST, GET, OPTIONS Access-Control-Max-Age 1728000 Connection Keep-Alive Content-Length 0 Content-Type text/plain Date Thu, 12 Dec 2013 12:39:27 GMT Server Apache-Coyote/1.1 access-control-allow-original Origin_IP_Address

POST Method Request and Response Headers

Request Headers

POST /servicePath HTTP/1.1

Host: crossDomain_IP_Address

User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:25.0) Gecko/20100101 Firefox/25.0

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8

Accept-Language: en-US,en;q=0.5

Accept-Encoding: gzip, deflate

X-PINGOTHER: pingpong

Origin: Origin_IP_Address

Connection: keep-alive

Pragma: no-cache

Cache-Control: no-cache

Content-Length: 0

Response Headers

HTTP/1.1 200 OK

Server: Apache-Coyote/1.1

Content-Type: text/json

Content-Length: 128

Date: Thu, 12 Dec 2013 12:39:27 GMT

ADDITIONAL INFO From the javascript two times the handler method has been called. At the First time, It is comeup with "currently the application is at 2" - readyState value. At the Second time, It is comeup with "Invocation Errors Occured 4(readyState value) and status code is 0 (response status code)". The second time response clearly says, invoking the service has been stopped by the same origin policy. But I dont know How to overcome from this problem and have to access the resource. Please help me by correcting my code.

like image 222
ArunRaj Avatar asked Dec 12 '13 12:12

ArunRaj


People also ask

What is HTTP preflight request?

A CORS preflight request is a CORS request that checks to see if the CORS protocol is understood and a server is aware using specific methods and headers. It is an OPTIONS request, using three HTTP request headers: Access-Control-Request-Method , Access-Control-Request-Headers , and the Origin header.

When preflight request is sent?

A preflight request is a small request that is sent by the browser before the actual request. It contains information like which HTTP method is used, as well as if any custom HTTP headers are present. The preflight gives the server a chance to examine what the actual request will look like before it's made.

What is HTTP CORS?

Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources.

How CORS work?

Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the first resource was served. A web page may freely embed cross-origin images, stylesheets, scripts, iframes, and videos.


1 Answers

Instead of dealing with X domain calls in javascript, why don't you develop a service local to your application that consumes the web service in the other domain, then you can call you local service from javascript.

I would suggest also, and alternatively, that you use jQuery to perform that Cross Domain Ajax call, see this link: http://www.pureexample.com/jquery/cross-domain-ajax.html.

There is no need to deal with XHR directly since you have jQuery to do it for you.

Hope this helps,

Regards.

like image 85
João Pinho Avatar answered Sep 28 '22 22:09

João Pinho