API = {
get_processed_autodesk_results : function(){
fetch('/api/results', {
method: 'get',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
}
}).then(res=>res.json())
.then(function(res) {
console.log(res);
});
}
}
setInterval(API.get_processed_autodesk_results,5000);
That is my code. I check the console and see that the fetch request is being executed twice every 5 seconds. I can't figure out why this is happening. Can anyone help? Thanks in advance
Its because your app component is a wrap in StrictMode . It is expected that setState updaters will run twice in strict mode in development. This helps ensure the code doesn't rely on them running a single time (which wouldn't be the case if an async render was aborted and later restarted).
The fetch() method takes one mandatory argument, the path to the resource you want to fetch. It returns a Promise that resolves to the Response to that request — as soon as the server responds with headers — even if the server response is an HTTP error status.
The fetch() method: Fetch API comes with a fetch () method that allows you to fetch data from all sorts of different places and work with the data fetched. It allows you to make an HTTP request, i.e., either a GET request (for getting data) or POST request (for posting data).
The Fetch API allows you to make network requests similar to XMLHttpRequest (XHR). The main difference is that the Fetch API uses Promises, which enables a simpler and cleaner API, avoiding callback hell and having to remember the complex API of XMLHttpRequest.
The additional fetch request you are seeing is an OPTIONS
request (pre-flight request) which is occurs when headers are passed in the request.
Excerpt from MDN:
Unlike “simple requests” (discussed above), "preflighted" requests first send an HTTP request by the OPTIONS method to the resource on the other domain, in order to determine whether the actual request is safe to send. Cross-site requests are preflighted like this since they may have implications to user data.
You can test requesting with and without headers and see what happens by checking developer tools here:
https://jsfiddle.net/219n4a0b/
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