GFL
GFL

Reputation: 1446

XMLHttpRequest causes two network events

I'm noticing when I have use a XMLHttpRequest in my script, that for each time it gets called two events appear in Chrome's network waterfall.

The first event has a type xhr and a size of around ~27bytes and the second event has a type of text/html and a size of 0bytes.

I've noticed it in the past and have looked over it, but now I'm noticing its causing the page it connects to for it to run twice.

Is this normal? Did I implement something incorrectly?

function example(){
console.log('ran'); // this shows the function only ran once
var form = new FormData(), xml = new XMLHttpRequest();
form.append('test', '...');
xml.upload.onprogress = function(e){something.style.width = (e.loaded*100/e.total) + "%";}
xml.onload = function(){alert('done');}
xml.open('POST', 'https://externaldomainexample.net', true);
xml.send(form);
}

Upvotes: 0

Views: 281

Answers (1)

peteredhead
peteredhead

Reputation: 2804

The two requests are being made because you are making a request to a different domain from which your page is hosted (cross origin). If you enable the "method" column in Chrome's network tab you'll see that the first request is an OPTIONS request, whereas the second is your POST request.

The first request is what's known as a Preflight request and asks the remote server what remote hosts are allowed to connect and what methods they are allowed to call. If this step fails, then you'll see an error in the browser saying the request has been "blocked by CORS policy".

If the preflight request is successful, then the second (POST) request is made.

Depending on how the server is configured, you may need to have it handle OPTIONS requests differently, so that it doesn't perform the same action twice.

Upvotes: 3

Related Questions