Medrod
Medrod

Reputation: 996

gwt grails Cross Domain Request

I wonder how can I make a cross domain request from a gwt application to a grails action. I know there is a wgt-plugin for grails but the development with this plugin is so slow (because I have to compile after each changes in the gwt-code). So I try to develop the gwt part separately and get the data from the grais application via ajax request. But the gwt application is running on a different server (gwt:port 8888, garils:port 8080). If I try to request the grails action I get this error in the browser:

XMLHttpRequest cannot load http://localhost:8080/MyApp/MyDomain/myAction. 
Origin http://127.0.0.1:8888 is not allowed by Access-Control-Allow-Origin.

I try to modify the response header in the grails action:

response.setHeader('Access-Control-Allow-Origin', "http://127.0.0.1:8888");

And if I call the action from a browser in the header I can find:

Access-Control-Allow-Origin:http://127.0.0.1:8888

But is do not solve the problem. What I do wrong?

Thanks in advance,

Medrod

UPDATE:

The solution is JSONP. On the GWT-Site my code looks like this:

private void jsonp() {

JsonpRequestBuilder jsonp = new JsonpRequestBuilder();
String URL = "http://localhost:8080/MyApp/myDomain/myAction";

jsonp.requestObject(URL, new AsyncCallback<JavaScriptObject>() {
    @Override
    public void onFailure(Throwable caught) {

    }
    @Override
    public void onSuccess(JavaScriptObject result) {

    }
});

}

And the grails code look like this:

def myAction = {
    def results = MyDomain.findAll()
    render "${params.callback}(${results as JSON})"
}

Thanks to Mic.

Upvotes: 0

Views: 1760

Answers (2)

dmotta
dmotta

Reputation: 1903

To solve this issue simply assign a variable to your json string into the eval

private final native MyJson evalJson(String json) /*-{
  eval('var res = ' + json);
  return res;
}-*/;

For more information, see "XMLHttpRequest cannot load. Origin is not allowed by Access-Control-Allow-Origin".

Upvotes: 0

Mic
Mic

Reputation: 25154

Web browsers have a built in security mechanism called Same Origin Policy (SOP) that prevent you to do that.

You can use JSONP, which is embedding you response in a Javascript function that will be called when the file is loaded and injected in your page as a SCRIPT tag.

For instance a response could be something like:

myCallbackFunction('a string parameter', {or:{a:json:'data'}}, ...)

And in your page you have a function:

myCallbackFunction(str, json, ...){...}

Upvotes: 1

Related Questions