I try to do a XMLHttpRequest from Javascript to a PHP script. Both are on the same server, but get the Error message:
myDomain.de/:1 Access to XMLHttpRequest at 'https://www.myDomain.de/test/lastId.php' from
origin 'https://myDomain.de' 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.
What’s the problem?
I tried Chrome and Edge as browser.
Thanks,
Stephan
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
header('Access-Control-Allow-Origin: https://www.myDomain.de');
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: *");
return "helloFromServer";
?>
function easy() {
const xhr = new XMLHttpRequest();
const url = "https://www.myDomain.de/test/lastId.php"
xhr.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log("succeed");
} else {
console.log("failure");
}
};
xhr.open("GET", url);
xhr.setRequestHeader("Access-Control-Allow-Origin", "https://www.myDomain.de");
xhr.setRequestHeader("Access-Control-Allow-Methods", "*");
xhr.setRequestHeader("Access-Control-Allow-Headers", "*");
xhr.send();
}