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
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
Share Improve this question asked Apr 25, 2018 at 18:59 Mike Johnson JrMike Johnson Jr 7962 gold badges14 silver badges34 bronze badges 9 | Show 4 more comments2 Answers
Reset to default 16The 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/
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()
setInterval
line is being called twice? – JLRishe Commented Apr 25, 2018 at 19:02setInterval()
call in some function that might get called more than once? – Pointy Commented Apr 25, 2018 at 19:03Template.render()
that gets called once when the page loads. – Mike Johnson Jr Commented Apr 25, 2018 at 19:08Template.render()
? Have you verified that it is only called once? – JLRishe Commented Apr 25, 2018 at 19:10