I recently found myself converting a function that calls a remote API, from returning a callback to returning a Promise. I thought that'd be a great opportunity to also replace the $.ajax call with a fetch call, as fetch already returns a Promise.
However, this specific call is a GET that actually expects a payload (containing key and return type). Specifically, I call it using:
$.ajax({
type: 'GET',
contentType: 'application/json; charset=utf-8',
url: config.serviceUrl,
data: {
apiKey: key,
format: 'json'
}
})
.done(data => {...})
.fail((jqXHR, textStatus, errorThrown) => {...});
However, fetch does not have a data property, and it throws an error if you try to send a body with a GET request (TypeError: Failed to execute 'fetch': Request with GET/HEAD method cannot have body). And according to the Chromium forums this is the expected behavior.
Bear in mind: I have absolutely no control of the external API, so mentioning that sending a payload with GET violates some API protocol, or suggesting I change the underlying call, is not helpful.
Is it possible to use fetch in this scenario? How?
bodyproperty of a fetch request to add data, such as aFormDataobject to the request. Also note thatFetchis highly experimental at this stage and not well supported. I'd personally stick with AJAX for now. It would also be helpful if you showed us the actualFetchrequest you've written