在Access-Control-Allow-Origin标头中找不到原始http:// localhost:8080

时间:2017-03-30 19:06:42

标签: html xmlhttprequest cross-domain

我正在我的localhost上运行一个html文件。我正在访问我服务器上的php文件。

Javascript在localhost上运行:

var url = "http://www.chartmygolf.com/_TEST_DELETE/exclude.php";
var method = "GET";
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
    // XHR for Chrome/Firefox/Opera/Safari.
    xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
    // XDomainRequest for IE.
    xhr = new XDomainRequest();
    xhr.open(method, url);
} else {
    // CORS not supported.
    xhr = null;
}

if (!xhr) {
    alert('CORS not supported');
    return;
}
// Response handlers.
xhr.onload = function (data) {
    var text = xhr.responseText;
    alert('Response: ' + text);
};
xhr.onerror = function (data) {
    alert('Woops, there was an error making the request.');
};
xhr.send();

我服务器上的php www.mysite.com:

<?php
$referrer = $_SERVER['HTTP_REFERER'];
$parts = parse_url($referrer);
$domain = $parts['host'];
header("Access-Control-Allow-Origin: http://" . $domain);
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
$arr = array("181K2", "4V419");
echo json_encode($arr);
?>

在Chrome和Edge中,它会进入alert('Woops, there was an error making the request.');

边缘错误:

SEC7120: Origin http://localhost:8080 not found in Access-Control-Allow-Origin header. SCRIPT7002: XMLHttpRequest: Network Error 0x80700013, Could not complete the operation due to error 80700013.

Chrome错误:

XMLHttpRequest cannot load http://www.chartmygolf.com/_TEST_DELETE/exclude.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

这让我疯了。我尝试了ajax,现在这种方法,我得到了不一致的结果。我已经在stackoverflow上读取了大量的线程,但没有任何答案可行。 (但是,这些线程似乎已经很久了。)

注意:如果我使用

,我会收到同样的错误

header("Access-Control-Allow-Origin: *");

请帮忙。我失去了对理智的全部控制。

1 个答案:

答案 0 :(得分:1)

行。找到了。我没有访问我的服务器上的PHP设置。它是Windows服务器。

将它放入php脚本所在目录中的web.config文件中就可以了。

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.webServer>
        <httpProtocol>
            <customHeaders>
                <add name="Access-Control-Allow-Origin" value="*" />
            </customHeaders>
        </httpProtocol>
    </system.webServer>
</configuration>

如果您不在Windows服务器上,则需要执行上述.htaccess等等。