I have to send a POST request with some data to a RESTful API. Right now I have a C program that creates a socket, connects with the host and successfully sends the POST request.
After some C magic, the request is formed as follows:
POST http://remotemanager.digi.com/ws/sci HTTP/1.1
Host: remotemanager.digi.com
Content-Type: text/xml
Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=
Content-Length: 123
<sci_request version="1.0"><ping><targets><device id="00000000-00000000-001234FF-FF56789A"/></targets></ping></sci_request>
Then I send it with send
from socket.h
. Everything works perfectly fine. After sending it, I receive:
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Set-Cookie: JSESSIONID=485A5984C8BB21B11BFB305145FAF3B9; Path=/ws/; HttpOnly;Secure
Cache-Control: no-store
Pragma: no-cache
Expires: Thu, 01 Jan 1970 00:00:00 GMT
Content-Type: application/xml;charset=ISO-8859-1
Content-Length: 195
Date: Thu, 09 Jan 2020 21:12:17 GMT
<sci_reply version="1.0"><send_message><device id="00000000-00000000-001234FF-FF56789A"><rci_reply version="1.1"><do_command target="RPC_request"/></rci_reply></device></send_message></sci_reply>
The problem is when I try to do this with HTML and Javascript. This is what I'm doing:
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Ping Gateway</title>
<script>
function send_request() {
var xml =
'<sci_request version="1.0">\n' +
'<send_message>\n' +
'<targets>\n' +
'<device id="00000000-00000000-001234FF-FF56789A"/>\n' +
'</targets>\n' +
'</ping>\n' +
'</sci_request>\n';
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (this.readyState == XMLHttpRequest.DONE && this.status == 200) {
}
else if (this.status == 401) {
document.getElementById("response").innerHTML = "Unauthorized!";
}
}
request.open("POST", "https://remotemanager.digi.com/ws/sci", true, "username", "password");
request.setRequestHeader("Content-Type", "text/xml");
request.send(xml);
}
</script>
</head>
<body>
<form onsubmit="send_request(); return false;" method="POST">
<input type="submit" value="Ping"></button>
</form>
<br>
<br>
<div id="response"></div>
</body>
</html>
But I get:
OPTIONS https://remotemanager.digi.com/ws/sci 401 (Unauthorized)
test.html:1 Access to XMLHttpRequest at 'https://username:[email protected]/ws/sci' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
So, if I'm performing the request form exactly the same computer, even the same folder, why does the C code works and the HTML/JS version triggers this CORS issue?