代码之家  ›  专栏  ›  技术社区  ›  antonj

XHR HEAD请求是否可能不遵循重定向(301 302)

  •  23
  • antonj  · 技术社区  · 14 年前

    是否可以发送一个xhrhttphead请求,只获取第一个请求的头响应,而不自动执行类似于301、302的重定向?我只对获取url的新位置感兴趣。例子:

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function(data) {
        if (xhr.readyState == 4) {
            if (xhr.status == 301 || xhr.status == 302) {
                // Get new location url don't GET it
            }
        }
    };
    xhr.open('HEAD', url, true);
    xhr.send();
    

    http://www.w3.org/TR/XMLHttpRequest/#infrastructure-for-the-send-method 似乎指定了应该遵循的请求,有没有办法阻止这种情况?

    4 回复  |  直到 14 年前
        1
  •  19
  •   Nick Craver    14 年前

    没有,这不是你能阻止的暴露行为。

    是因为 the spec you linked already ,指定的行为是XmlHttpRequest应该 透明地 不幸的是,遵循重定向…在封面下,而不是以你能阻止的方式。

        2
  •  6
  •   Community CDub    4 年前

    W3C规范要求自动遵循重定向,如下所示: @Nick suggested in the other answer considered by the W3C for a future version of this specification :

    • 错误事件和onerror属性;
    • 进度事件和onprogress属性;
    • 已经建议使用计时器,可能是ontimeout属性;
    • 属性以禁用以下重定向;
    • 文本/html文档的responseXML;
    • 跨站点XMLHttpRequest;
    • 处理字节流的responseBody;
    • 重写MIME类型以修复MIME类型;

    但是,在所有浏览器都实现之前,我不会屏住呼吸。您可能需要使用服务器端代理来处理此问题。只需写一个简短的脚本 HEAD 使用您喜爱的服务器端语言/框架进行请求,然后使用Ajax查询此服务。您还可以通过代理向第三方域发出请求,这是一个积极的副作用。

        3
  •  0
  •   Community CDub    8 年前

    现在这是可能的!至少在Firefox和Chrome浏览器中是这样

    当我找到答案时,我几乎绝望了: https://stackoverflow.com/a/8056313/995007

    前任:

        var xhttp = new XMLHttpRequest();
        xhttp.onload = function() {
            console.log(xhttp.responseURL); // Here you are!
        };
        xhttp.open('GET', 'https://www.ddd.com/news', true);
        xhttp.send();
    
        4
  •  -11
  •   Community CDub    8 年前

    可能的 .

    当重定向太多时,主要浏览器将停止重定向。在chrome中,您将得到一个错误ERR\u TOO\u MANY\u REDIRECTS after 20 times REDIRECTS。像这样测试代码(另存为重读.php):

    <?php
    $times = isset($_GET['t']) ? intval($_GET['t']) : 1;
    if ( $times < 20) {
        header("Location: redir.php?t=".strval($times+1));
    } else {
        header("Location: http://the.final.target.url/which.will.give.you.a.301.header.but.you.do.not.want.to.follow.it");
    }
    

    然后你会发现重定向将停止,因为我们例外。也适用于xhr和公共JS,如 (new Image).src="some.url" .

    还有一点,浏览器之间的最大重定向限制是不同的。你可以通过测试找到数字重读.php你自己,或者从这个主题中找到它: In Chrome, how many redirects are "too many"?