Failed to load resource: Request timed out on Safa

2019-06-15 01:05发布

问题:

We have a web application working correctly for over a year now on most browsers. Recently we discovered it is not working that well on Safari.

A lot of actions end up with the following error : Failed to load resource: Request timed out. Funny thing is the action is actually performed correctly after that (most of the time).

When looking into the error, it seems to happen when there is an ajax request.

First I tried to change the ajax timeout setting by doing the following :

 $.ajax({
      "type"      : methode,
      "dataType"  : "json",
      "url"       : url,
      "async"     : async,
      "data"      : donneesEnvoyees,
      "timeout"   : 60000
 })

That didn't change anything at all, error is actually showing up after about 10 seconds which is less than the timeout defined.

After reading a bit on the internet, I saw some answer about specifying no-cache so that safari doesn't keep the post parameters in cache. I cannot say I fully understand that, but I still tried the following way :

$.ajax({
     "type"      : methode,
     "headers"   : { "cache-control": "no-cache" }, <-- added this line
     "dataType"  : "json",
     "url"       : url,
     "async"     : async,
     "data"      : donneesEnvoyees,
     "timeout"   : 60000
 })

As you can guess, I still get the same error.

Do you have any idea of what is happening? Why is this error happening only on Safari and not other browsers? How to fix it?

回答1:

Set the async: true on your ajax settings. It will make the browser hold the connection and just close after receive the response back.



回答2:

I got the same issue. Fixed by adding CORS header and response status code as 200

 res.header('Access-Control-Allow-Origin', '*');
 res.status(200);

How & Why

After digging into the error by reading jQuery's source code, I realized the real problem is the XMLHttpRequest in jQuery+Safari is calling onError with a http status code0. So I added CORS headers and give it a 200 status code to solve the problem.



回答3:

I think your issue will be fixed if you remove dataType : "json" from the code if the return from your ajax page is not a proper JSON string. I've noticed that the $.ajax() doesn't go to the success function if the dataType : "json" is provided and the return data is not of the type JSON.

PS
There are certain things like the AJAX settings keywords type, dataType, url etc are not supposed to be in double quotes. Even though code will work even with the current way, but proper way is what I mentioned.

$.ajax({
      type      : methode,
      dataType  : "json",
      url       : url,
      async     : async,
      data      : donneesEnvoyees,
      timeout   : 60000,
      success   : function(data){
                alert('success');
      }
});

I presume you have added a success function with this ajax call which you can use to use different actions based on the result.