[英]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 做一些事情:
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)一起使用;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/ ):
This article https://jakearchibald.com/2015/thats-so-fetch/ contains a more detailed description.这篇文章https://jakearchibald.com/2015/thats-so-fetch/包含更详细的描述。
ReadableStream
instances as request bodies is yet to come )没有上传进度(对ReadableStream
实例作为请求主体的支持尚未到来)mozAnon
flag or the AnonXMLHttpRequest
constructor)没有办法不发送 cookie(除了使用非标准mozAnon
标志或AnonXMLHttpRequest
构造函数)FormData
instances无法返回FormData
实例fetch
's no-cors
mode没有等效于fetch
的no-cors
模式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.