CORB, JSON and JSONP
So, you managed to write your REST-API that return JSON format response for every REST-API calls. You tested it out using ‘wget’ / ‘curl’, your REST-API works fine.
Now you want to call, the REST-API, using AJAX on your favorite browser. The JSON format response never shows up, and your browser debugging utility, complain CORS(Cross-Origin Read Blocking). CORS is a way to protect you from ‘something’ malicious. I don’t know intimately what CORS [please educate yourself, if you want to know it in detail], but it is really ‘pain in the ass’ to the core-level for me. Enough about CORS!
JSON format
{ “id” : 1000, “name” : “juniarto”}
JSONP format
callbackfunction( {“id”:1000, “name” : “juniarto”});
Solution:
Basically what you need to do is to ensure your REST-API returns JSONP format, instead of JSON.
AJAX:
$.ajax({
type: "GET",
url : "http://172.20.98.140:8000/training-set/0",
dataType: 'jsonp'
}).done(function(jsondata, status, xhr){
console.log(jsondata.x[0]);
console.log(status);
console.log(xhr.status);
}).fail(function(xhr, status, error){
console.log("error");
});
When you include dataType: ‘jsonp’ your request to the REST-API will looks like:
You need to grab jQuery112404902942447054407_1561539848873&_=1561539848876 , and return it together with your JSON response in your REST-API, something like this:
JSONP response:
jQuery112404902942447054407_1561539848873&_=1561539848876({“id”:1000, “name” : “juniarto”})
You can easily do it using the following in your REST-API code:
callback = request.args.get(‘callback’)
'{0}({1})'.format(callback,jsondata)
You don’t need to parse the JSONP response in your AJAX. You can access it directly, like:
jsondata.id
That’s all, folks!