A (not so) simple web architecture. Part III. Cross-Domain Configuration

Previously, you were shown how to set up a java REST service and a javascript webpage to call the service. This assumed that the webpage resides on the same server as the REST service. If you were to move that page to another server, say an apache server to do some work on php, then you might find a strange error such as

XMLHttpRequest cannot load http://localhost:8080/kodingnotes/rest/foo/read?input=blah. Origin http://localhost is not allowed by Access-Control-Allow-Origin.

It violates the same origin page policy. Basically, “Under the same origin policy, a web page served from server1.example.com cannot normally connect to or communicate with a server other than server1.example.com. An exception is the HTML <script> element”

Here’s your solution: jsonp

Here’s the quick cheat sheet of what you need to do.

On the Server side
Fortunately, Jersey supports jsonp. You just need to create a wrapper method that returns the json in a padded script like so:

@GET
@Produces({"application/x-javascript"})
@Path("/read/jsonp")
public JSONWithPadding getFooP(
    @QueryParam("callback") @DefaultValue("fn") String callback,
    @QueryParam("input") String input) {
	return new JSONWithPadding(new GenericEntity<Foo>(getFoo(input)) {},
								   callback);
}

On the client side
You just need to redirect your url to the jsonp version and modify the dataType to “jsonp”

var matchUri = "http://localhost:8080/kodingnotes/rest/foo/read/jsonp";

function getFoo(input) {
  $.ajax({
    type: "GET",
    dataType: "jsonp",
    url: matchUri + "?input=" + input,
    success: function(data){
       alert("Success");
    }
 });
}
Advertisements
Tagged , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: