admin管理员组文章数量:1134587
I know that Fetch API uses Promise
s and both of them allow you to do AJAX requests to a server.
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
).
What extra capabilities does the Fetch API have?
I know that Fetch API uses Promise
s and both of them allow you to do AJAX requests to a server.
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
).
What extra capabilities does the Fetch API have?
Share Improve this question edited Jul 30, 2019 at 20:46 Alexander Abakumov 14.5k16 gold badges96 silver badges132 bronze badges asked Feb 22, 2016 at 9:05 ilyabasiukilyabasiuk 4,6004 gold badges23 silver badges36 bronze badges 8 | Show 3 more comments4 Answers
Reset to default 213There are a few things that you can do with fetch and not with XHR:
- You can use the Cache API with the request and response objects;
- You can perform
no-cors
requests, getting a response from a server that doesn't implement CORS. You can't access the response body directly from JavaScript, but you can use it with other APIs (e.g. the Cache API); - Streaming responses (with XHR the entire response is buffered in memory, with fetch you will be able to access the low-level stream). 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/):
- Abort a request (this now works in Firefox and Edge, as @sideshowbarker explains in his comment);
- Report progress.
This article https://jakearchibald.com/2015/thats-so-fetch/ contains a more detailed description.
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
- 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) - doesn't support
--allow-file-access-from-files
(chromium)
XHR
- there's no way to not send cookies (apart from using the non-standard
mozAnon
flag or theAnonXMLHttpRequest
constructor) - can't return
FormData
instances - doesn't have an equivalent to
fetch
'sno-cors
mode - always follows 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
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
fetch('./api/some.json')
.then((response) => {
response.json().then((data) => {
...
});
})
.catch((err) => { ... });
fetch, according to the specs, will throw a TypeError if the URL to be fetched contains credentials ("Request cannot be constructed from a URL that includes credentials").
This may sound reasonable (for security) and neglectable, because an additional "Authorization" header could be used if needed.
However, there's a problem if fetch inside a page shall load data relative to the base url of the page and if that page's URL has credentials itself. The browser will construct an URL for fetch('data.json')
that contains credentials taken from the page and throw an error.
To me this appears like a browser bug - it's building the URL and could simply leave out credentials (what it does every other time anyway replacing it magically by "Authorisation" header). However, as it happens on both Chrome and Firefox, this may be intentional (although, IMO, the specs may leave room for another interpretation as well).
XMLHttpRequest, on the other hand, would load the requested resource happily even with credentials (see network tab in developer tools).
Hence, under certain circumstances, the behaviour of the page will change or even lead to an error - which we had to learn the hard way. We ended up building an absolute URL by using windows.location
data.
本文标签: javascriptFetch API vs XMLHttpRequestStack Overflow
版权声明:本文标题:javascript - Fetch API vs XMLHttpRequest - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736773025a1952188.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
fetch(url).then(function(data) (...));
is not simpler than usingXMLHttpRequest
to do the same thing? It may have lots of other features, but geez, it sure is simpler to use for common things. It IS a cleaned up API. – jfriend00 Commented Feb 22, 2016 at 16:13