I deployed the php application with Apache with basic authentication enabled.
When accessing from local with ajax, the following error occurs.
Failed to load https://(myapp).herokuapp.com/api.php?mode=xxx: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 401.
My .htaccess setting is like this.
Header set Access-Control-Allow-Origin "*"
AuthUserFile /app/.htpasswd
AuthType Basic
AuthName "Restricted Access"
Require valid-user
And, My program is like this.
<button>Go!</button><br>
<textarea name="" id="result" cols="100" rows="10"></textarea>
<script src="./jquery-3.3.1.min.js"></script>
<script src="./jquery.base64.min.js"></script>
<script>
var uri = "https://(myapp).herokuapp.com/api.php?mode=xxx";
$('button').on('click', function() {
$.ajax({
url: uri,
success: function(response) {
$('textarea').val(response);
},
error: function(xhr, textStatus, errorThrown) {
console.log(textStatus + " : " + errorThrown);
},
beforeSend: function(xhr) {
var credentials = $.base64.encode("user:pass");
xhr.setRequestHeader("Authorization", "Basic " + credentials);
}
});
});
</script>
If basic authentication is disabled, data can be get successful.
So I think that it is Apache's problem rather than PHP.