When sending CROS Ajax request, sometimes you may found that before every request you make, there will be a OPTION
request sent.
It’s quite annoying and slows down your data request since the actually request has to wait the OPTION request to finish.
According to the CORS strategy (highly recommend you read about it) You can’t just force the browser to stop sending OPTION request if it is necessary.
There’s two way you can work around it
- Make sure your request is a “Simple Request”
- Set
Access-Control-Max-Age
for the OPTION request
Simple request
A simple cross-site request is one that meets all the following conditions:
The only allowed methods are:
– GET
– HEAD
– POST
Apart from the headers set automatically by the user agent (e.g. Connection, User-Agent, etc.), the only headers which are allowed to be manually set are:
– Accept
– Accept-Language
– Content-Language
– Content-Type
The only allowed values for the Content-Type header are:
– application/x-www-form-urlencoded
– multipart/form-data
– text/plain
A simple request will not cause a pre-flight OPTION request. So just check your request to see if any of it breaks the rules above.
Set a cache for the OPTION check
If you request just can’t be a “Simple Request”,
You can set a Access-Control-Max-Age
for the OPTION request, so that it will not check the permission again until it is expired.
Access-Control-Max-Age gives the value in seconds for how long the response to the preflight request can be cached for without sending another preflight request.