9

I am looking at my ajax request in network tab in chrome and I noticed every ajax request I do happens twice.

First one is a 204 and then followed up with 200. My ajax call is only being hit once so I am not sure why there are 2.

Edit

So it seems to have to do with Cors, which I have just set to star (*) for testing.

I guess there is not to much I can do to not have it do 2 requests, but what really gets me is why it takes so long, I looking at google chrome network and on my page these 204 took anywhere from 110ms to 1.97 seconds.

chobo2
  • 83,322
  • 195
  • 530
  • 832

2 Answers2

13

That's a consequence of the CORS - Cross-origin resource sharing "protocol".

When doing requests do other domains, the browser do a request before your request, asking for the server if it can proceed with that request.

This request uses the method OPTIONS and should have no content, just response headers, that's why the response code is 204 (no content). After confirming that the request is allowed, the browser proceed with your request, that now will return 200 (or any other) status code.

Elias Soares
  • 9,884
  • 4
  • 29
  • 59
  • So my front end ajax code is hitting my api which is on it's own subdomain, I guess there is no way around this? It just kinda anoying to see these request and for some reason seem kind slow, sometimes to get this 204 back it can take anywhere from 110milliseconds to 1.97 seconds, then the 200 will take around the same time. – chobo2 May 22 '19 at 05:39
  • there are some sittuations that you can avoid it, but almost everytime you need it :-( – Elias Soares May 22 '19 at 18:02
  • yeah, figured, do you know what might cause the lag between the request? It seems like it should be very fast. – chobo2 May 22 '19 at 20:21
7

When you try to send a AJAX request to a different domain, you are violating the same-origin policy.

Server that you are sending the request allows cross domain requests. In the process, there should be a preflight call and that is the HTTP OPTION call.

So, you are having two responses for the OPTION and your result.

Tan Sang
  • 1,897
  • 1
  • 16
  • 28