没有“访问控制允许来源”错误,即使标头在我的服务器端代码上


No 'Access-Control-Allow-Origin' error even though the header is there on my server side code

>更新:由于某种原因,服务器端脚本具有 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.
服务器

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

这也许能够帮助你使用 php 标头进行 CORS

"正确处理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!";
}