No' Access-Control-Allow-Origin'即使我的服务器端代码上有标题,也会出错

时间:2015-01-30 00:30:38

标签: javascript php cors

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

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

1 个答案:

答案 0 :(得分:0)

这可能可以帮助您CORS with php headers

&#34;正确处理CORS请求有点复杂。这是一个能够更充分(和正确)响应的功能。&#34;

**
 *  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!";
}