maxivis maxivis - 1 month ago 12
Javascript Question

Can't make JSONP call

this problem is really driving me crazy... I have 2 java web application: appA that publish a REST service which returns some object (which contains an image) in json format, and appB that consumes the service and shows the image. In my local machine it works (though I see the CORS error) but now I'm using a web environment (Layershift) and I'm getting an error "NetworkError: 404 Not Found - http://app-demo.j.layershift.co.uk/myservice/get/c80e9306105f4448?callback=myCallback&_=1477167892656"

I've been reading lot of examples of CORS and JSONP but I can't find what's wrong with my code, can anybody give a hint?

Controller in appA:

@RestController
public class MyController {
@RequestMapping(value="/myservice/get/{somevar}")
public @ResponseBody MyObject getMyObject (@PathVariable String somevar, HttpServletRequest request, HttpServletResponse response) {
MyObject obj = new MyObject();
//some logic
return obj;
}
}


ControllerAdvice in appA:

@ControllerAdvice
public class JsonpAdvice extends AbstractJsonpResponseBodyAdvice {
public JsonpAdvice() {
super("myCallback");
}
}


javascript code with jsonp call in appB:

(function($) {
function myCallback(data) {
if (data.status == "OK") {
//shows the image contained
}
}

$.fn.callWithJsonP = function(somevar) {
$.ajax({
url: "myservice/get/" + somevar,
type: 'GET',
dataType: "jsonp",
jsonpCallback: "myCallback"
});
};
})(jQuery);


Any help would be appreciated, regards

PS: also tried adding the directive "Header add Access-Control-Allow-Origin "*"" in Apache, but same result.

Answer

Finally can make the JSONP call, didn't solve my problem, but I'm able to make the call, so I'll post the changes.
First of all, in the main controller I'm not using @ResponseBody, I've changed it like this:

@RestController
public class MyController {
    @RequestMapping(value="/myservice/get/{somevar}")
    public MappingJacksonValue getMyObject (@RequestParam String callback, @PathVariable String somevar, HttpServletRequest request, HttpServletResponse response) {
        MyObject obj = new MyObject();
        //some logic
        MappingJacksonValue value = new MappingJacksonValue(obj);
        value.setJsonpFunction(callback);
        return value;
    }
}

Notice the return type is MappingJacksonValue (thanks to JSONP with Spring 3.0 and Jackson), and the javascript code is this:

$.fn.callWithJsonP = function(somevar) {
    var url = "/myservice/get/" + somevar + "?callback=myCallback";
    $.getJSON(url, function(data) {
        if (data.value.status == "OK") {
            //show the image contained
        }
    });
}

There was no need to define a function called "myCallback". I've tested in my local machine and it is working.
Thanks everybody for your suggestions.

Comments