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.
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.
-
What does your
beforeSend
method logic looks like? – MinusFour Commented Feb 6, 2021 at 18:01 - @MinusFour As well? for the current application? – 1nslg Commented Feb 6, 2021 at 18:04
-
Yes, how do you actually use it. jQuery basically uses this method to access a version of a XHR object. The interface is very different with
fetch
. – MinusFour Commented Feb 6, 2021 at 18:10 - So do you think I should handle the actions before the end with XHR object? – 1nslg Commented Feb 6, 2021 at 18:15
-
No, there's no XHR object with
fetch
. It's a different interface. Whatever you did with the XHR object insidebeforeSend
will most likely have a different way to do so withfetch
. – MinusFour Commented Feb 6, 2021 at 18:35
1 Answer
Reset to default 5Solved 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?format=${format}`).then((response) => {
return response.json();
}).then((data) => {
console.log(data.ip);
});
}
ipGetAddress('json') // return local ip address..