自定义标头在PHP中给出CORS错误

时间:2015-02-03 15:22:14

标签: php cross-domain cors cross-domain-policy custom-headers

我正在尝试基于REST的跨域请求。这两个域都将托管在同一台服务器上。

domain1:http://testdata.local - 用于在domain2上请求REST API的应用程序。

domain2:http://api.testdata.local - 用于处理来自domain1的REST API调用

每个rest api调用都有一些domain2所需的自定义标头。

现在当我通过ajax向domain2调用rest API请求时,我收到了CORS阻止错误。

下面是我正在尝试的代码:

关于domain2上的示例api请求的PHP代码:

class mytest{

    public function setOriginPolicy() {
        if (isset($_SERVER['HTTP_ORIGIN']) && $_SERVER['HTTP_ORIGIN'] == 'http://testdata.local') {
            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, PUT, DELETE, OPTIONS");
            }
            if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
                header("Access-Control-Allow-Headers:{$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
            }

            exit(0);
        }
    }

    public function testrequest(){
            $this->setOriginPolicy
            $result['config_status'] = 1;
            $result['config_msg'] = "request ok";
            echo json_encode($result);

    }
}

来自domain1的AJAX调用:

var url = "http://api.testdata.local/mytest/testrequest";
$.ajax({
    type: 'GET',
    url: url,
    async: true,
    crossDomain:true,
    //jsonpCallback: 'jsonCallback',
    contentType: "application/x-www-form-urlencoded",
    headers:{"API_KEY":"andapikey","APP_VERSION":"1.0","CONFIG_VERSION":"1.0","AUTH_TOKEN": "4a6b1e610e81fa19c76a557049e9fa19"
    },
    /*beforeSend: function( xhr ) {
        xhr.setRequestHeader("API_KEY", "andapikey"); 
        xhr.setRequestHeader("APP_VERSION", "1.0");
        xhr.setRequestHeader("CONFIG_VERSION", "1.0");
        xhr.setRequestHeader("AUTH_TOKEN", "4a6b1e610e81fa19c76a557049e9fa19");
    },*/
    success: function(json) {
        console.log(json);
    },
    error: function(e) {
        console.log(e.message);
    }
});

如果我禁用标题,我会收到回复。

请建议

1 个答案:

答案 0 :(得分:1)

解决方案:

在.htaccess中的allow origin标头中添加了自定义标头。

点击链接http://benjaminhorn.io/code/setting-cors-cross-origin-resource-sharing-on-apache-with-correct-response-headers-allowing-everything-through/

特别感谢本杰明。

下面是我的.htaccess

Header always set Access-Control-Allow-Origin "http://testdata.local"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header always set Access-Control-Max-Age "1000"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin,API_KEY,APP_VERSION,CONFIG_VERSION,AUTH_TOKEN"
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On
    RewriteCond %{REQUEST_METHOD} OPTIONS
    RewriteRule ^(.*)$ $1 [R=200,L]

    # Redirect Trailing Slashes...
    RewriteCond %{REQUEST_METHOD} !OPTIONS
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_METHOD} !OPTIONS
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>