viernes, 25 de enero de 2013

[GWT] XMLHttpRequest cannot load. Origin is not allowed by Access-Control-Allow-Origin

I am developing an app front end  with GWT and this connect to other app that publish AppEngine Endpoints services. 
(Estoy desarrollando una aplicación  front end con GWT que se conecta a otra app que publica servicios rest en AppEngine usando Google Cloud EndPoints).

But, I is generating some problems (is not allowed by Access-Control-Allow-Origin.): 
(Pero, esto  me esta generando  algunos problemas).

The app GWT  call endpoint using  RequestBuilder. and the Endpoint app is other app with other domain. and both was deployed in https://appengine.google.com
(La app GWT llama a los servicios rest' endpoints' usando RequestBuilder. y la app endpoint es otra app con otro dominio. Ambas fueron deployadas en https://appengine.google.com).

Domains of the Apps:
-xappgwtx.appspot.com (GWT).
-xappendpointsx.appspot.com (Google Cloud Endpoints).

GWT Code:

public String getDevice(String id) {
String url = URL_SERVICE_BASE + "deviceendpoint/v1/device/get/" + id;
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
logger.info("::::::::::::sendRequest:::::::");
try {
builder.sendRequest(null, new RequestCallback() {
public void onResponseReceived(Request request, Response response) {
logger.info("response=" + response.getText() + " request:" + request);
resp = response.getText();
if (response.getStatusCode() == 200) {
System.out.println("response=" + response.getText());
logger.info("response=" + response.getText());
}
}

public void onError(Request request, Throwable exception) {
logger.info("onError response=" + exception.getMessage());
resp = exception.getMessage();
exception.printStackTrace();
}
});
} catch (RequestException e) {
logger.info("exception=" + e.getMessage());
e.printStackTrace();

}
return resp;
}

Chrome Console:

After much research in lists, stackoverflow and other forum, solve the problem
(Luego  de mucha investigación en listas y stackoverflow llegue a solucionar el  problema)

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

* Before:

  public static native JavaScriptObject fromJson(String json) /*-{

    return eval("(" + json + ")");

  }-*/;
  
  public final String toJson() {
    return new JSONObject(this).toString();
  }
  
  protected BaseJso() {
  }

* After: 

public class BaseJso extends JavaScriptObject {



public static native JavaScriptObject fromJson(String json) /*-{
eval('var res = ' + json);
return res;
}-*/;

public final String toJson() {
return new JSONObject(this).toString();
}

protected BaseJso() {
}

}

References: