Reputation: 332
I'm using static html/javascript pages (no php, etc.)
I have a static HTML web page. When the page loads, it makes an XMLHttpRequest to a target server on another domain, waits for the response, and parses the response JSON.
function executeRequest() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var response = JSON.decode(xhttp.responseText);
alert(response.access_token)
alert(response.expires_in)
}
};
var tmpURL = "https://target.url.com/oauth2/access_token"
xhttp.open("POST", tmpURL, true);
xhttp.send();
}
XMLHttpRequest cannot load [target.url.com] No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://local.url.com' is therefore not allowed access.
To rule out a problem with CORS, I can request the URL with a form. When the user clicks the Submit button, it brings a successful response.
<form method="POST" action="https://target.url.com/oauth2/access_token">
... form inputs here
<input type="submit" value="Submit form">
</form>
Why is the target server responding differently to the xmlHttpRequest than the Form?
Upvotes: 0
Views: 660
Reputation: 707866
You have a CORS issue.
XMLHttpRequests
are subject to CORS rules.
<form method="POST" action="http://xxx">
posts done purely with HTML are not subject to CORS rules.
It's as simple as that.
Part of the reason this cross origin form post is allowed is that the browser will change the browser window to display the response from the form post so the cross origin site controls what happens next. That is not the case with XMLHttpRequest
where the requesting page controls what happens next as no page is automatically loaded or displayed after an XMLHttpRequest
. So, it's easier to cause mischief with XMLHttpRequest
than it is with a form post.
See Cross Domain Form POSTing for some further explanation.
Upvotes: 3