Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent multiple OPTIONS request for the same domain

I am trying to develop a single page application (SPA) that uses as endpoint a domain that is different from the one hosted in the SPA domain (ie: site.com and site-api.com or api.site.com).

Access Control headers are already set up in the back-end, Max-Age included, however it does not seem to work.

Here's an example of what happens if I perform the same call multiple times:

google dev tools

These are the server headers:

  • Access-Control-Allow-Headers: AUTHORIZATION,CONTENT-TYPE
  • Access-Control-Allow-Methods: PATCH
  • Access-Control-Allow-Origin: http://tovertaal.test:3000
  • Access-Control-Max-Age: 600

Shouldn't Max-Age 600 prevent every other OPTIONS request within 600 seconds from the first OPTIONS request?

The server endpoint is http://tovertaal-api.test.

like image 498
GiamPy Avatar asked Jul 10 '18 15:07

GiamPy


People also ask

How can we avoid preflight requests?

Another way to avoid Preflight requests is to use simple requests. Preflight requests are not mandatory for simple requests, and according to w3c CORS specification, we can label HTTP requests as simple requests if they meet the following conditions. Request method should be GET , POST , or HEAD .

Why am I getting an options request instead of a GET request?

It uses methods other than GET or POST. Also, if POST is used to send request data with a Content-Type other than application/x-www-form-urlencoded, multipart/form-data, or text/plain, e.g. if the POST request sends an XML payload to the server using application/xml or text/xml, then the request is preflighted.

What is Httpoptions?

The HTTP OPTIONS method requests permitted communication options for a given URL or server. A client can specify a URL with this method, or an asterisk ( * ) to refer to the entire server.

What is a CORS preflight request?

A CORS preflight request is a CORS request that checks to see if the CORS protocol is understood and a server is aware using specific methods and headers. It is an OPTIONS request, using three HTTP request headers: Access-Control-Request-Method , Access-Control-Request-Headers , and the Origin header.


1 Answers

I have finally discovered what was the issue. It seems like Chrome DevTools, when disable cache is active, also disables CORS Origin cache, so it keeps triggering OPTIONS request for stuff that should have been cached already.

Make sure to keep caching enabled if you want to test it!

like image 65
GiamPy Avatar answered Nov 06 '22 06:11

GiamPy