Avoiding preflight OPTIONS requests with CORS Avoiding preflight OPTIONS requests with CORS asp.net asp.net

Avoiding preflight OPTIONS requests with CORS


I think this post (How to apply CORS preflight cache to an entire domain) pretty much says it all - there is not much you can do about this

The one simple solution is to add a reverse proxy to the proxy/webserver serving your angular app (e.g. nginx) to route your RESTful calls via the same domain, e.g. appdomain.com/api --> apidomain.com.


Another solution that seems to be working OK for me. Instead of setting up a proxy and needing to route to the same domain, it is possible to return the preflight request directly from nginx and therefore reducing the time required by the preflight request down to just a couple of milliseconds.

Here is a simple snippet that can be used with nginx.

 location / {    if ($request_method = 'OPTIONS') {        add_header 'Access-Control-Allow-Origin' '*';        add_header 'Access-Control-Allow-Credentials' 'true';        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';        add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization';        add_header 'Access-Control-Max-Age' 1728000;        add_header 'Content-Type' 'text/plain charset=UTF-8';        add_header 'Content-Length' 0;        return 204;     }}

Once the preflight request is successful, it is then possible to simple add "Access-Control-Allow-Origin" and other necessary stuff to the 'GET','POST' requests, etc...