I am trying to submit a post request using an endpoint URL. I am sending the content-type as application/json and two header values for username and password. When I try to access it via Postman, I get 200 response code along with tokenId and successUrl but when the same is being done via the below JavaScript code, I get 401. The same is working when I try to get is done via JSP and Java. Me, not being a Javascript expert, am unable to figure out the reason. I read the CORS articles and am not sure why cross-domain is not a problem with Java/JSP code but occurs for JavaScript. Below is the code:
<!DOCTYPE html>
<html>
<body>
<h2>REST</h2>
<button type="button" onclick="myFunc()">Request data</button>
<p id="demo"></p>
<script>
function myFunc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("POST", "Endpoint URL entered here", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.setRequestHeader("X-OpenAM-Username", "username entered here");
xhttp.setRequestHeader("X-OpenAM-Password", "password entered here");
xhttp.send();
}
</script>
</body>
</html>
The error that comes on Chrome browser is as below:
Access to XMLHttpRequest at 'Endpoint URL' 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.
a.html:23 POST 'Endpoint URL' net::ERR_FAILED
EDIT1: The error that comes on Firefox browser is as below:
XHROPTIONS 'Endpoint URL' [HTTP/1.1 401 Unauthorized 2025ms]
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at 'Endpoint URL'. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at 'Endpoint URL'. (Reason: CORS request did not succeed).
Please let me know what exactly am I doing wrong.