Search code examples
javascriptfetch

beforeSend: function() in fetch API


I am currently migrating the use of ajax to the fetch, however I am needing a parameter/function the Ajax native beforeSend: function(). I would like to perform the same action without requiring an implementation in fetch (a creation of a new class for example)

jQuery $.ajax structure:

$.ajax({
    url: '...',
    type: 'post',
    data: {...},
    beforeSend: function() {
        // perform the action..
    },
    success: function(response, status, xhr) {
        // receive response data
    }
});

JavaScript fetch structure:

fetch('...').then((response) => {
    return response.text();
}).then((data) => {
    console.log(data);
});

How do I determine such a function without needing an implementation or creating a new class on fetch. Is there any means or only implementation? because of my searches I only found implementations like CustomFetch (Is there a beforesend Javascript promise) and others.


Solution

  • Solved problem!

    No need to implement and/or create a new fetch class. Using only parameters as "function inside function". I hope you can help others!

    function ipGetAddress(format) {
      requestFetch = function() {
        // perform the action..
        console.log('** beforeSend request fetch **');
        return fetch.apply(this, arguments);
      }
    
      requestFetch(`https://api.ipify.org?format=${format}`).then((response) => {
        return response.json();
      }).then((data) => {
        console.log(data.ip);
      });
    }
    
    ipGetAddress('json') // return local ip address..