默认 GET 行为 'XMLHttpRequest' 和 'fetch' 之间的差异



就发送到url服务器的最终请求而言,下面的XHRGet函数和FetchGet函数之间有什么区别吗?它们是否具有不同的默认标头或类似内容?在使用这两种方法进行网络爬行时,我注意到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());
}

谢谢!

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

最新更新