Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using fetch instead of jQuery's ajax for a GET API call

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?

like image 415
Traveling Tech Guy Avatar asked Dec 24 '22 00:12

Traveling Tech Guy


1 Answers

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)
like image 136
TimoStaudinger Avatar answered Jan 23 '23 02:01

TimoStaudinger