Getting ckan.js working in a browser requires CORS setting
Hi I just want to share how to get ckan.js to work in a browser so that you don't need to waste your time figuring it out.
Below you will see to javaScript programs that look similar. They do the same thing. But one works and the other dont.
In order to get the version that is running in the browser working you need to enable CORS on your CKAN server. You do this by adding this line in the configuration file and restarting the server.
ckan.cors.origin_allow_all = true
After you do this the browser version will also work.
Node version
Run it by typing
node ckan_dataset_list.js
The node version ckan_dataset_list.js
var CKAN = require('ckan')
var myAPIkey = "";
var resource_id = "3ae312b4-0e9b-4542-92b7-cf017b586f0c";
var myCKANhost = "http://urbalurba.no";
var client = new CKAN.Client(myCKANhost, myAPIkey);
client.action('datastore_search', { resource_id: resource_id }, function(err, result) {
console.log(err);
//console.log(result);
console.log("We can read all records in a dataset:", JSON.stringify(result));
})
Browser version
The browser version ckan_dataset_list_browser.js
var myAPIkey = "";
var resource_id = "3ae312b4-0e9b-4542-92b7-cf017b586f0c";
var myCKANhost = "http://urbalurba.no";
var client = new CKAN.Client(myCKANhost, myAPIkey);
client.action('datastore_search', { resource_id: resource_id }, function(err, result) {
console.log(err);
//console.log(result);
console.log("We can read all records in a dataset:", JSON.stringify(result));
document.getElementById("app").innerText = "Result:" + JSON.stringify(result);
})
The browser version html file
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="http://okfnlabs.org/ckan.js/ckan.js"></script>
</head>
<body>
<h1>Listing a dataset resource</h1>
<div id="app"></div>
<script src="ckan_dataset_list_browser.js"></script>
</body>
</html>
In my plugin, I've gotten around this by using a jQuery call, but I agree that this would be a nice addition to the library. Looking around, it seems like bermi/jsonp-client could be a good way to go here.
I've left some instructions in this JsFiddle if anyone's struggling with this during development. In production, proxying your requests to CKAN through a server is a better option than whitelisting CORS to the world.