简体   繁体   中英

Allow headers in cross-domain ajax request

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"

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"

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM