Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my fetch request being called twice?

Tags:

javascript

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

like image 487
Mike Johnson Jr Avatar asked Apr 25 '18 18:04

Mike Johnson Jr


People also ask

Why API is called twice in react?

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).

How do fetch requests work?

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.

Is a fetch request a GET request?

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).

What is the difference between fetch and request?

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.


1 Answers

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/

like image 72
Mathias W Avatar answered Nov 06 '22 14:11

Mathias W