I am trying to refactor a client to an old backend from XMLHttpRequest to use the Fetch API instead, and I am having a hard time figuring out what the Fetch API equivalent of xhr.send(file) is in the code below.
input.addEventListener('change', function(event) {
var file = event.target.files[0];
var url = 'https://somedomain.com/someendpoint';
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'image/jpeg');
xhr.send(file);
}
May 17, 2021 3 min read API. The Fetch API allows you to make network requests similar to XMLHttpRequest (XHR). The main difference is that the Fetch API uses Promises, which enables a simpler and cleaner API, avoiding callback hell and having to remember the complex API of XMLHttpRequest.
It is an improvement over the XMLHttpRequest API. The main difference between Fetch and XMLHttpRequest is that the Fetch API uses Promises, hence avoiding callback hell . If you are new to promises then check out JavaScript Promises: an Introduction .
The Fetch API is a modern alternative to XMLHttpRequest . The generic Headers, Request, and Response interfaces provide consistency while Promises permit easier chaining and async/await without callbacks.
Fortunately, the response object that fetch() returns includes an ok property that we can use to determine whether the API call was successful or not. While the Fetch API uses an XMLHttpRequest object under the hood, they don't contain all of the same properties.
fetch
can take a second argument, init
, which specifies advanced options of the request. In particular, you can specify the method
and the body
options:
fetch(url, {
method: 'POST',
headers: new Headers({
"Content-Type": "image/jpeg",
}),
body: file,
})
You can also pass the same options to the Request
constructor.
body
must a Blob, BufferSource, FormData, URLSearchParams, or USVString object. Fortunately, File objects are just a special kind of Blobs, and can be used everywhere where Blobs are accepted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With