I want to perfrom cross-domain request from localhost to localhost:81, but I constantly get CORS-Header'Access-Control-Allow-Origin' missing. But I have set the header in postHere.php. I also tried header('Access-Control-Allow-Origin: *'); and it is also not working?
postHere.php
<?php
switch ($_SERVER['HTTP_ORIGIN']) {
case 'http://localhost':
case 'https://localhost':
header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
break;
}
HTML file in localhost from which I want to send to localhost:81
<html>
<head>
<script src="//code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<script>
$.ajax({
type: 'POST',
url: 'http://localhost:81/postHere.php',
crossDomain: true,
data: '{"some":"json"}',
dataType: 'json',
success: function(responseData, textStatus, jqXHR) {
var value = responseData.someKey;
},
error: function (responseData, textStatus, errorThrown) {
alert('POST failed.');
}
});
</script>
</body>
</html>
You should enable your server on the second origin (in your case localhost:81, though you should probably use 8081 instead) to allow cross-origin requests. Check mozilla guides on that.
Links: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS https://developer.mozilla.org/en-US/docs/Glossary/CORS