【问题标题】:Origin http://localhost:8080 not found in Access-Control-Allow-Origin header在 Access-Control-Allow-Origin 标头中找不到来源 http://localhost:8080
【发布时间】:2017-08-24 21:13:00
【问题描述】:

我正在本地主机上运行一个 html 文件。我正在访问我服务器上的一个 php 文件。

Javascript 正在本地主机上运行:

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();

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

<?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: *");

请帮忙。我失去了理智。

【问题讨论】:

    标签: html xmlhttprequest cross-domain


    【解决方案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 等效项。

    【讨论】:

      猜你喜欢
      • 2016-08-06
      • 1970-01-01
      • 2013-04-09
      • 2012-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-12
      相关资源
      最近更新 更多