即使标题存在,CORS也会失败

时间:2015-04-18 18:51:41

标签: php cross-domain cors

我正在使用CORS请求将数据发布到不同域上的php脚本。我收到了错误:

  

阻止跨源请求:同源策略禁止读取   远程资源位于' mydomain'(原因:CORS标题   '访问控制允许来源'丢失)。

我已经使用以下代码在php中设置了标题。

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: OPTIONS, GET, POST");

我也试过这个post

中的代码

这是供参考的JavaScript代码

$.ajax(url, {
    type:"POST",
    dataType:"json",

    data: {
        name:"something"
    },

    success:function(data, textStatus, jqXHR) {
        alert("success");
    },

    error: function(jqXHR, textStatus, errorThrown) {
        alert("failure");
    }
});

响应标头

Age:1
Cache-Control:max-age=900
Connection:keep-alive
Content-Length:356
Content-Type:text/html; charset=utf-8
Date:Sun, 19 Apr 2015 04:26:27 GMT
Server:Microsoft-IIS/7.5
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET

请求标题

Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Cache-Control:no-cache
Connection:keep-alive
Content-Length:14
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
DNT:1
Host:www.jurney.co
Origin:http://isabelinc.in
Pragma:no-cache
Referer:http://isabelinc.in/jurney/testcors.html
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36 

但我没有运气。 任何帮助表示赞赏

1 个答案:

答案 0 :(得分:0)

试试这个:

<?php
    // 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!";
?>