草庐IT

javascript - Socket.IO 和 IE8 - jsonp 轮询连接总是失败

coder 2025-01-17 原文

值得注意:以下是通过 https 跨域完成的。老实说,我不认为这是问题所在,因为在 IE10、Chrome 和 FF 中一切正常。我的猜测是它可能是 IE8 中的 XDomainRequest 对象变体?虽然不确定。

下面的sendLoginRequest方法是最先调用的方法。下面还提供了所有其他支持代码。

这一切都非常简单,但不确定为什么 IE8 会失败。

function WrappedSocket(data, session_string) {
    var clientSocket = io.connect('https://xxxxxxxx/socketio', { query: "session=" +       encodeURIComponent(session_string), transports: ['jsonp-polling'] });
    clientSocket.socket.on("connect", function () { console.log("CONNECT_SUCCEED"); });
    clientSocket.socket.on("connect_failed", function () { console.log("CONNECT_FAILED");    });
    clientSocket.socket.on("reconnect_failed", function () {    console.log("RECONNECT_FAILED"); });
    clientSocket.socket.on("error", function (eobj) { console.log("Socket error " + eobj);    });
    console.log("Made a socket that is talking");
}

var my_socket;


function set_up_socket(data, sessionString) {
    setSession(data.responseText);
    my_socket = new WrappedSocket(data, sessionString);
    my_socket.socket.emit("message", "Howdy!");
}

function sendLoginRequest(loginCode, nextRequest) {
    var xhr = createCORSRequest('POST', 'https://xxxxx/login', false);
    var sessionString = 'xxxx';

    if ("withCredentials" in xhr) {
        xhr.addEventListener("load", function () {
            set_up_socket(this, sessionString);
        }, false);
    }
    else {
        xhr.onload = function () {
            set_up_socket(this, sessionString);
        };
    }

    xhr.send();
    }

function createCORSRequest(method, url, onload) {
    xhrObj = new XMLHttpRequest();
    if ("withCredentials" in xhrObj) {
        // Check if the XMLHttpRequest object has a "withCredentials" property.
        // "withCredentials" only exists on XMLHTTPRequest2 objects. 
        if (onload) {
            xhrObj.addEventListener("load", onload, false);
        }
        xhrObj.open(method, url, true);
        xhrObj.withCredentials = true;
    } else if (typeof XDomainRequest != "undefined") {
        // Otherwise, check if XDomainRequest.
        // XDomainRequest only exists in IE, and is IE's way of making CORS requests.

        xhrObj = new XDomainRequest();
        xhrObj.open(method, url);
        if (onload) {
            xhrObj.onload = onload;
        }
    } else {
        // Otherwise, CORS is not supported by the browser.
        xhrObj = null;
    }
    return xhrObj;
    }

我在控制台和 Fiddler 中看到的错误 轮询实际上正在发生,但每次轮询都会出现相同的失败:

LOG:CONNECT_FAILED
'f.parentNode' is null or not an object
'f.parentNode' is null or not an object
LOG:CONNECT_FAILED
'f.parentNode' is null or not an object
'f.parentNode' is null or not an object
LOG:CONNECT_FAILED
'f.parentNode' is null or not an object
'f.parentNode' is null or not an object
LOG:CONNECT_FAILED
'f.parentNode' is null or not an object
'f.parentNode' is null or not an object
LOG:CONNECT_FAILED
'f.parentNode' is null or not an object
'f.parentNode' is null or not an object
LOG:CONNECT_FAILED
'f.parentNode' is null or not an object
'f.parentNode' is null or not an object

......................

(你明白了,这在轮询时一遍又一遍地发生。)

同样,您可以看到每个请求一个接一个地触发,来自服务器的所有 200 个响应都导致 CONNECT_FAILED 和 socket.io.js 文件中的 JS 错误。

最后,这里是客户端上的 socket.io.js 文件中的代码,它打破了上面在控制台屏幕截图中看到的错误(“f.parentNode 为 null 或不是对象”)。我知道该对象为空,但我不明白为什么它为空。

........

if (this.isXDomain() && !io.util.ua.hasCORS) {
  var insertAt = document.getElementsByTagName('script')[0]
    , script = document.createElement('script');

  script.src = url + '&jsonp=' + io.j.length;
  insertAt.parentNode.insertBefore(script, insertAt);

  io.j.push(function (data) {
      complete(data);
      script.parentNode.removeChild(script);  // *** BREAKS HERE!! ***
  });

.........

最佳答案

根据 this answer ,我不认为 IE8 支持 XMLHttpRequest() 对象或 XDomainRequest()(或大多数其他对象)的 .addEventListener() 方法,它似乎是后来添加的)。

尝试将该部分代码重写为:

xhr.onload=function () {
        set_up_socket(this, sessionString);
    };

如果您想为其他现代浏览器保留相同的语法,您可以通过将其包装在条件中来回填:

if(typeof xhr.addEventListener === undefined)
{
    xhr.onload=function () {
        set_up_socket(this, sessionString);
    };
}

不知道是否能解决问题,但可能有所帮助。

MDN 说 "More recent browsers, including Firefox, also support listening to the XMLHttpRequest events via standard addEventListener APIs in addition to setting on* properties to a handler function." .同样,我不确定,因为他们没有说明哪些浏览器以及何时使用,但我最好能告诉您 IE8 不支持它。

关于javascript - Socket.IO 和 IE8 - jsonp 轮询连接总是失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18637953/

有关javascript - Socket.IO 和 IE8 - jsonp 轮询连接总是失败的更多相关文章

  1. ruby-openid:执行发现时未设置@socket - 2

    我在使用omniauth/openid时遇到了一些麻烦。在尝试进行身份验证时,我在日志中发现了这一点:OpenID::FetchingError:Errorfetchinghttps://www.google.com/accounts/o8/.well-known/host-meta?hd=profiles.google.com%2Fmy_username:undefinedmethod`io'fornil:NilClass重要的是undefinedmethodio'fornil:NilClass来自openid/fetchers.rb,在下面的代码片段中:moduleNetclass

  2. ruby-on-rails - Rails - 乐观锁定总是触发 StaleObjectError 异常 - 2

    我正在学习Rails,并阅读了关于乐观锁的内容。我已将类型为integer的lock_version列添加到我的articles表中。但现在每当我第一次尝试更新记录时,我都会收到StaleObjectError异常。这是我的迁移:classAddLockVersionToArticle当我尝试通过Rails控制台更新文章时:article=Article.first=>#我这样做:article.title="newtitle"article.save我明白了:(0.3ms)begintransaction(0.3ms)UPDATE"articles"SET"title"='dwdwd

  3. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  4. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

  5. Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting - 2

    1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里

  6. ruby - 为什么不能使用类IO的实例方法noecho? - 2

    print"Enteryourpassword:"pass=STDIN.noecho(&:gets)puts"Yourpasswordis#{pass}!"输出:Enteryourpassword:input.rb:2:in`':undefinedmethod`noecho'for#>(NoMethodError) 最佳答案 一开始require'io/console'后来的Ruby1.9.3 关于ruby-为什么不能使用类IO的实例方法noecho?,我们在StackOverflow上

  7. ruby-on-rails - 使用 javascript 更改数据方法不会更改 ajax 调用用户的什么方法? - 2

    我遇到了一个非常奇怪的问题,我很难解决。在我看来,我有一个与data-remote="true"和data-method="delete"的链接。当我单击该链接时,我可以看到对我的Rails服务器的DELETE请求。返回的JS代码会更改此链接的属性,其中包括href和data-method。再次单击此链接后,我的服务器收到了对新href的请求,但使用的是旧的data-method,即使我已将其从DELETE到POST(它仍然发送一个DELETE请求)。但是,如果我刷新页面,HTML与"new"HTML相同(随返回的JS发生变化),但它实际上发送了正确的请求类型。这就是这个问题令我困惑的

  8. ruby - 在 Mechanize 中使用 JavaScript 单击链接 - 2

    我有这个:AccountSummary我想单击该链接,但在使用link_to时出现错误。我试过:bot.click(page.link_with(:href=>/menu_home/))bot.click(page.link_with(:class=>'top_level_active'))bot.click(page.link_with(:href=>/AccountSummary/))我得到的错误是:NoMethodError:nil:NilClass的未定义方法“[]” 最佳答案 那是一个javascript链接。Mechan

  9. ruby - Ruby 导入的方法总是私有(private)的吗? - 2

    最好用一个例子来解释:文件1.rb:deffooputs123end文件2.rb:classArequire'file1'endA.new.foo将给出错误“':调用了私有(private)方法'foo'”。我可以通过执行A.new.send("foo")来解决这个问题,但是有没有办法公开导入的方法?编辑:澄清一下,我没有混淆include和require。另外,我不能使用正常包含的原因(正如许多人正确指出的那样)是因为这是元编程设置的一部分。我需要允许用户在运行时添加功能;例如,他可以说“run-this-app--includefile1.rb”,应用程序的行为将根据他在file1

  10. ruby-on-rails - 为什么 do/end 和 {} 不总是等价的? - 2

    这个问题在这里已经有了答案:关闭11年前。PossibleDuplicate:RubyblockandunparenthesizedargumentsWhatisthedifferenceorvalueoftheseblockcodingstylesinRuby?我一直认为以下只是同一件事的两种表达方式:[1,2,3].collect{|i|i*2}[1,2,3].collectdo|i|i*2end但是我在我的一个ERB模板中发现了一些奇怪的行为,这两种语法似乎在做两件不同的事情。这段代码效果很好:m))}}%>但是当我将其重写为:m))endend%>...我最终得到了我的@men

随机推荐