【问题标题】:Userscript cross-origin request failing用户脚本跨域请求失败
【发布时间】:2018-12-02 13:35:06
【问题描述】:

我的 AJAX 函数:

function ajaxQuery(url, method, param, async, onsuccess, onfailure) {
    var xmlHttpRequest = new XMLHttpRequest();
    var callback = function(r) { r.status==200 ? (typeof(onsuccess)=='function' && onsuccess(r)) : (typeof(onfailure)=='function' && onfailure(r)); };

    if(async) { xmlHttpRequest.onreadystatechange = function() { if(xmlHttpRequest.readyState==4) { callback(xmlHttpRequest); } } }
    xmlHttpRequest.open(method, url, async);
    xmlHttpRequest.setRequestHeader('X-REQUESTED-WITH', 'XMLHttpRequest');
    xmlHttpRequest.withCredentials = true;
    if(method == 'POST') { xmlHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); }
    xmlHttpRequest.send(param);
    if(!async) { callback(xmlHttpRequest); }
}

函数调用:

ajaxQuery('http://example.net/index.php', 'GET', null, true, function(r) {
    tmp.innerHTML = r.responseText;
    nlt = [].map.call(tmp.querySelectorAll('.nlt'), function(x) { return x.textContent; });
});

在 PHP 中设置的标题:

header('Access-Control-Allow-Origin: https://example.com');
header('Access-Control-Allow-Origin: https://www.example.com');
header('Access-Control-Allow-Origin: http://example.net');
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Credentials: true');
if(!preg_match('%https?:\/\/(www\.)?example\.com%', $_SERVER['HTTP_REFERER']) && !preg_match('%https?:\/\/example\.net%', $_SERVER['HTTP_REFERER'])) { die('No way!'); }

我从使用 https 的页面调用用户脚本,而我的域使用 http。当我通过 http 尝试 AJAX 时,我得到 (Firefox) Blocked loading mixed active content。如果我将查询 URL 切换为 https,则错误将更改为 Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource,即使我的 PHP 脚本明确允许来自外部站点的请求。我错过了什么?

在这个特定示例中,我的网站是“http://example.net”,外部网站是“https://www.example.com

【问题讨论】:

  • 当你只使用header('Access-Control-Allow-Origin: *');时它会起作用吗?
  • @spielerds,不,它没有。相同的Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource 错误。
  • 这是整个错误信息?它也应该包含被阻止的域。可以? :)
  • @spielerds,被屏蔽的域是我的个人域 ("example.net/index.php")。出于匿名目的,我不会透露真实的域。
  • 您可以访问外部站点吗?您可以更改该外部域的 CORS 政策吗?

标签: javascript php cors cross-domain


【解决方案1】:

如果协议不匹配,则不可能通过 AJAX、JSONP 或 iFrames 获取外部资源,至少在 Firefox 和 Chromium 中,由于愚蠢的“mixed content”限制。我的网站在 http 上运行,并且为其编写用户脚本的网站已强制执行 https(这意味着尝试通过 http 请求其页面会自动重定向到 https,因此我什至无法通过选择 http 来解决限制) .

【讨论】:

    【解决方案2】:

    只要您允许,Access-Control-Allow-Origin 标头的值应与 Origin 标头相同。

    所以。你想要多个域。我建议您使用“正则表达式”

    【讨论】:

    • 你能进一步解释一下“正则表达式”吗?
    • @NicoHaase,特别是考虑到我已经为多个域使用了正则表达式...
    猜你喜欢
    • 1970-01-01
    • 2017-12-27
    • 2015-01-28
    • 2012-02-26
    • 1970-01-01
    • 2013-10-24
    • 1970-01-01
    • 1970-01-01
    • 2014-03-29
    相关资源
    最近更新 更多