How do you POST to Kodi with fetch()?
#1
Hi all,

I'm new to all this JSON-RPC stuff, and what I have been working on is a JavaScript function that POSTs to the Kodi box at a specified IP and port.

json:

var settingsLoaded = {"kodiIP": localStorage.getItem("settingsKey_kodiIP"),
"kodiPort": localStorage.getItem("settingsKey_kodiPort")};
var constructRequest = {"jsonrpc": "2.0",
"method": "",
"params": {},
"id": 1};
var getToKodiTesting = function(kodiMethod, inParams) {
if (typeof kodiMethod !== "string") {
console.log("[getToKodiTesting] type kodiMethod: "+typeof kodiMethod);
console.log("[getToKodiTesting] type inParams: "+typeof inParams);
console.log("[getToKodiTesting] Supplied options incorrect, not doing anything.");
return;
} else {
constructRequest.method = kodiMethod;
if (typeof inParams == "object") {
constructRequest.params = inParams;
} else {
delete constructRequest.params;
}
console.log("[getToKodiTesting] Attempting POST request.")
return window.fetch("http://"+settingsLoaded.kodiIP+":"+settingsLoaded.kodiPort+"/jsonrpc", {method: "POST",
mode: "cors",
body: JSON.stringify(constructRequest),
headers: {"Content-Type": "application/json"}
}).then(function(response) {
if (response.status !== 200) {
console.log("[getToKodiTesting] Unable to connect to Kodi. Response status: "+response.status+".");
return;
} else {
console.log("[getToKodiTesting] Got response for method call '"+kodiMethod+"'. Data is: "+response.body);
console.log("[getToKodiTesting] Returning parsed JSON to caller.");
response.json().then(function(parsedJSON) {
return parsedJSON;
}).catch(function(error) {
console.log("[getToKodiTesting] Cannot parse recieved JSON. Error: "+error.message+".")
});
}
constructRequest.method = "";
constructRequest.params = {};
}).catch(function(error) {
console.log("[getToKodiTesting] Error in fetch: "+error.message);
return;
});
}
}

The IP is set to the local IP of the device running Kodi and port is set to the one in Kodi settings.

The problem is that I'm met with a Cross-Origin Request Blocked error, with it complaining that CORS header 'Access-Control-Allow-Origin' is missing.

Is there something else I have to do?
Reply
#2
Ok, nevermind everyone, I found a Promise-ified XMLHttpRequest solution called Atomic that works very well. Basically a near drop-in replacement for fetch() that just works.
Reply
#3
Could you please post an example for us? I have the same problem, I had a working solution with GET and never updated Kodi. Now, I use the current version and I have problems moving my "webpage solution" to POST because of CORS.
Thank you!
Reply

Logout Mark Read Team Forum Stats Members Help
How do you POST to Kodi with fetch()?0