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?
jQuery's ajax
function simply appends data
to the URL as URL parameters for GET
requests:
data
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests.
Source
Using fetch, you can either do it manually, or you could use an approach similar to that:
var url = new URL("http://youapi.com")
var data = {
apiKey: key,
format: 'json'
}
Object.keys(data).forEach(key => url.searchParams.append(key, data[key]))
fetch(url)
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