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

“XMLHttpRequest”和“fetch”的默认GET行为之间的差异?

  •  0
  • user993683  · 技术社区  · 8 年前

    两者之间有什么不同吗 XHRGet FetchGet 根据发送到的服务器的最终请求,函数如下所示 url ? 它们是否有不同的默认标题,或者类似的内容?在使用这两种方法进行网络爬行时,我注意到 fetch 往往比 XMLHttpRequest ,我不知道为什么会这样。

    (async () => {
      console.log( await XHRGet("https://stackoverflow.com") );
      console.log( await fetchGet("https://stackoverflow.com") );
    })();
    
    function XHRGet(url) {
      return new Promise(resolve => {
        let req = new XMLHttpRequest();
        req.addEventListener("load", function() { resolve(this.responseText); });
        req.open("GET", url);
        req.send();
      });
    }
    
    function fetchGet(url) {
      return fetch(url).then(res => res.text());
    }
    

    谢谢

    1 回复  |  直到 8 年前
        1
  •  2
  •   Anne    8 年前

    fetch() 默认情况下不包括凭据。我想改变这一点 https://github.com/whatwg/fetch/pull/585 . 在那之后,它们应该几乎相同。(还有一些解码差异。 fetch() 将始终使用UTF-8。 XMLHttpRequest 更宽容一点。但这不会导致失败,只是可能会导致不同的结果字符串。)