Using fetch instead of jQuery ajax to call the GET API

I recently discovered that I am converting a function that calls the remote API from return callback to return Promise. I thought it was a great opportunity to replace a call with a $.ajaxcall fetch, as it fetchalready returns Promise.

However, this particular call is GETone that actually expects the payload (containing the key and return type). In particular, I call this 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, it fetchdoes not have a property data, and it throws an error if you try to send bodywith a request GET( TypeError: Failed to execute 'fetch': Request with GET/HEAD method cannot have body). And according to the Chromium forums this is the expected behavior.

: API, , GET - API , .

fetch ? ?

+4
2

jQuery ajax data URL- URL GET :

< >

. , . URL- GET.


, , :

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)
+2
   var headers = new Headers();
   headers.append("Content-Type", "application/json; charset=utf-8");
   fetch(config.serviceUrl + "?apiKey=" + key + "&format=json", 
     {headers:headers, method:"GET"}
   ).then(response => response.json())
   .then(json => /* do stuff with `json` */)
   .catch(err => console.error(err));

$.ajax().

+3

Source: https://habr.com/ru/post/1659636/


All Articles