Mike Johnson Jr
Mike Johnson Jr

Reputation: 796

Why is my fetch request being called twice?

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

Upvotes: 9

Views: 17943

Answers (2)

Officialk
Officialk

Reputation: 26

I also faced a similar problem but it turns out it was because my routes were going through the service worker which again requested and returned the request so the server got 2 requests 1 from the main fetch an another from the service workers fetch.
EDIT facepalm yea I am new to pwas and all so was using return instead of respondWith()

Upvotes: 0

Mathias W
Mathias W

Reputation: 1521

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/

Upvotes: 16

Related Questions