gpt4 book ai didi

javascript - Firefox XMLHttpRequest 在 302 响应上设置错误标志

转载 作者:行者123 更新时间:2023-11-30 06:49:39 34 4
gpt4 key购买 nike

我有一个由 servlet 驱动的网络应用程序,它会在一段时间不活动后通过重定向到登录页面使用户 session 超时。我在检查这一点的网络客户端上有适当的代码,基本上类似于以下内容:

function error(request, errtype) {
if (request.status == 302) {
// Display a "timed out" dialog, then:
window.location = request.getResponseHeader("Location");
}
}

但是,最近这个方案失效了;超时时,request.status 为 0。使用 Firebug 我可以看到返回了相同的 HTTP 302 响应。

我仔细阅读了 XMLHttpRequest 的规范,发现了这一部分:

If the redirect does not violate security (it is same origin for instance), infinite loop precautions, and the scheme is supported, transparently follow the redirect while observing the same-origin request event rules.

Otherwise, this is a network error.

我什至不知道客户端应该自动遵循他们为响应 Ajax 请求而获得的重定向;我关心的浏览器以前没有这样做,因为我上面的代码曾经工作过。我最近升级了我的 Firefox 版本,它现在可能更严格地遵循规范。规范规定的网络错误可以解释我看到的零响应代码。但是,我得到的重定向是同一台主机(尽管在不同的端口上),不应该出现无限循环,并且该方案仍然是 HTTP,所以我不明白为什么我会收到网络错误.

有什么想法吗?

最佳答案

你是如何实现这个功能的?如果你只是在 200 状态下将它发送到“错误”,显然这是行不通的......

request.onreadystatechange = function( )
{
if( this.readyState == 4 )
{
// if we got a 200
if( this.status == 200 ){ /* cool */ }

// if we got anything else
else { error( this, this.status ); }
}
};

但我假设您知道这一点。此外,您可能应该在 window.location 的末尾包含 .href 并且可能包含默认位置以防万一

// Display a "timed out" dialog, then:
window.location.href = request.getResponseHeader("Location") || defaultPage;

如果这不起作用,您可能想在 onreadystatechange 方法中尝试不同的状态,因为某些浏览器可能会将非 200 状态解释为错误。这些可能是(来自您正在阅读的同一规范):

0 (if it's considered aborted after unset, though unlikely)
2 (headers-sent) as that 302 code is actually a HTTP header

祝你好运!

关于javascript - Firefox XMLHttpRequest 在 302 响应上设置错误标志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1924551/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com