Reputation: 26281
The first Ajax request receives a response, but not the second which includes a header. How can I allow headers to be included in a cross-domain Ajax request.
Note - I expect I need to make a server-side change, and https://stackoverflow.com/a/32140436/1032531 also says so, but doesn't say how to make those changes. Also, I am not looking for a jQuery only solution.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Testing</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
$.ajax({
type:'POST',
url:'http://otherdomain.example.com/ajax.php',
})
$.ajax({
type:'POST',
url:'http://otherdomain.example.com/ajax.php',
headers: {"X-Test-Header": "test-value"},
})
});
</script>
</head>
<body></body>
</html>
FF response to the second Ajax request:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://otherdomain.example.com/ajax.php. (Reason: missing token 'x-test-header' in CORS header 'Access-Control-Allow-Headers' from CORS preflight channel).
Chrome responds to the second as:
XMLHttpRequest cannot load http://otherdomain.example.com/ajax.php. Request header field X-Test-Header is not allowed by Access-Control-Allow-Headers in preflight response. Apache is set up as
follows:
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
Header set Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept, Authorization, Client-Security-Token, Accept-Encoding"
Upvotes: 4
Views: 8939
Reputation: 558
You can get rid of this error by using a .htaccess rule. Just create a .htaccess
file.on the home directory (or append these lines to it if you already have one)
Header set Access-Control-Allow-Origin "*"
This will globally allow cross orgin. If you want for only one page you can use
<?php header("Access-Control-Allow-Origin: *"); ?>
At the top of the page
Upvotes: 0
Reputation: 26281
It seems that each header must explicitly be listed and I added x-test-header
to Access-Control-Allow-Headers
.
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
Header set Access-Control-Allow-Headers "x-test-header, Origin, X-Requested-With, Content-Type, Accept"
Upvotes: 6