【问题标题】:No 'Access-Control-Allow-Origin' error even though the header is there on my server side code即使标头在我的服务器端代码中,也没有“Access-Control-Allow-Origin”错误
【发布时间】:2015-01-30 00:30:38
【问题描述】:

更新: 出于某种原因,服务器端脚本有 Unicode 字符,当我通过记事本保存它时,它切换到 ANSII 并且工作正常。我不确定 Unicode 的东西是如何进入那里的,但现在它正在工作。希望这篇文章能在未来对某人(很可能是我)有所帮助。


尽管我有正确的标题,但我收到了 CORS 错误。这是一个月前的工作,我的服务器或客户端代码没有任何改变。

服务器端

<?php
header('Access-Control-Allow-Origin: https://mywebsite.com');  
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Content-Range, Content-Disposition, Content-Description');
header('Access-Control-Allow-Credentials: true');

客户端错误

XMLHttpRequest cannot load https://serverside.com/serversidecode.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://mywebsite.com' is therefore not allowed access.

服务器端代码完全运行,但不会将成功数据发送回我的客户端服务器。

【问题讨论】:

    标签: javascript php cors


    【解决方案1】:

    这也许能帮到你CORS with php headers

    “正确处理 CORS 请求有点复杂。这是一个可以更全面(和正确)响应的函数。”

    **
     *  An example CORS-compliant method.  It will allow any GET, POST, or OPTIONS requests from any
     *  origin.
     *
     *  In a production environment, you probably want to be more restrictive, but this gives you
     *  the general idea of what is involved.  For the nitty-gritty low-down, read:
     *
     *  - https://developer.mozilla.org/en/HTTP_access_control
     *  - http://www.w3.org/TR/cors/
     *
     */
    function cors() {
    
        // Allow from any origin
        if (isset($_SERVER['HTTP_ORIGIN'])) {
            header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
            header('Access-Control-Allow-Credentials: true');
            header('Access-Control-Max-Age: 86400');    // cache for 1 day
        }
    
        // Access-Control headers are received during OPTIONS requests
        if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    
            if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
                header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         
    
            if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
                header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
    
            exit(0);
        }
    
        echo "You have CORS!";
    }
    

    【讨论】:

      猜你喜欢
      • 2017-09-05
      • 2018-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-01
      • 1970-01-01
      • 2017-10-29
      相关资源
      最近更新 更多