简体   繁体   English

获取 API 与 XMLHttpRequest

[英]Fetch API vs XMLHttpRequest

I know that Fetch API uses Promise s and both of them allow you to do AJAX requests to a server.我知道 Fetch API 使用Promise并且它们都允许您向服务器发出 AJAX 请求。

I have read that Fetch API has some extra features, which aren't available in XMLHttpRequest (and in the Fetch API polyfill, since it's based on XHR ).我读过 Fetch API 有一些额外的功能,这些功能在XMLHttpRequest中不可用(在 Fetch API polyfill 中,因为它基于XHR )。

What extra capabilities does the Fetch API have? Fetch API 有哪些额外功能?

There are a few things that you can do with fetch and not with XHR:你可以用 fetch 而不是 XHR 做一些事情:

  • You can use the Cache API with the request and response objects;您可以将 Cache API 与请求和响应对象一起使用;
  • You can perform no-cors requests, getting a response from a server that doesn't implement CORS.您可以执行no-cors请求,从未实现 CORS 的服务器获取响应。 You can't access the response body directly from JavaScript, but you can use it with other APIs (eg the Cache API);您不能直接从 JavaScript 访问响应正文,但您可以将其与其他 API(例如缓存 API)一起使用;
  • Streaming responses (with XHR the entire response is buffered in memory, with fetch you will be able to access the low-level stream).流式响应(使用 XHR,整个响应缓冲在内存中,使用 fetch 您将能够访问低级流)。 This isn't available yet in all browsers, but will be soon.这并非在所有浏览器中都可用,但很快就会出现。

There are a couple of things that you can do with XHR that you can't do yet with fetch, but they're going to be available sooner or later (read the "Future improvements" paragraph here: https://hacks.mozilla.org/2015/03/this-api-is-so-fetching/ ):您可以使用 XHR 做一些您无法使用 fetch 做的事情,但它们迟早会可用(阅读此处的“未来改进”段落: https://hacks.mozilla .org/2015/03/this-api-is-so-fetching/ ):

  • Abort a request (this now works in Firefox and Edge, as @sideshowbarker explains in his comment);中止请求(现在可以在 Firefox 和 Edge 中使用,正如@sideshowbarker 在他的评论中所解释的那样);
  • Report progress.报告进展。

This article https://jakearchibald.com/2015/thats-so-fetch/ contains a more detailed description.这篇文章https://jakearchibald.com/2015/thats-so-fetch/包含更详细的描述。

fetch拿来

  • missing a builtin method to consume documents缺少使用文档的内置方法
  • no way to set a timeout yet没有办法设置超时
  • can't override the content-type response header无法覆盖内容类型响应标头
  • if the content-length response header is present but not exposed , the body's total length is unknown during the streaming如果 content-length 响应头存在但未公开,则在流传输期间主体的总长度未知
  • will call the signal's abort handler even if the request has been completed即使请求已完成,也会调用信号的中止处理程序
  • no upload progress (support for ReadableStream instances as request bodies is yet to come )没有上传进度(对ReadableStream实例作为请求主体的支持尚未到来

XHR XHR

  • there's no way to not send cookies (apart from using the non-standard mozAnon flag or the AnonXMLHttpRequest constructor)没有办法发送 cookie(除了使用非标准mozAnon标志AnonXMLHttpRequest构造函数)
  • can't return FormData instances无法返回FormData实例
  • doesn't have an equivalent to fetch 's no-cors mode没有等效于fetchno-cors模式
  • always follow redirects始终遵循重定向

The answers above are good and provide good insights, but I share the same opinion as shared in this google developers blog entry in that the main difference (from a practical perspective) is the convenience of the built-in promise returned from fetch上面的答案很好,提供了很好的见解,但我与这篇google 开发者博客文章中的观点相同,主要区别(从实际角度来看)是从fetch返回的内置承诺的便利性

Instead of having to write code like this而不是必须编写这样的代码

function reqListener() {
    var data = JSON.parse(this.responseText);
}

function reqError(err) { ... }

var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.onerror = reqError;
oReq.open('get', './api/some.json', true);
oReq.send();

we can clean things up and write something a little more concise and readable with promises and modern syntax我们可以用promise和现代语法清理东西并写出更简洁易读的东西

fetch('./api/some.json')
    .then((response) => {
        response.json().then((data) => { 
            ... 
        });
    })
    .catch((err) => { ... });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM