I've written an API using Django REST Framework. For authentication, I'm using django-oauth2-provider: https://github.com/caffeinehit/django-oauth2-provider
I have cors configured in my settings page like so (using Corsheaders middleware.)
MIDDLEWARE_CLASSES = (
...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
)
CORS_ORIGIN_ALLOW_ALL = True # Dangerous (using for testing purposes)
My client application is built with Angular JS. However, every time we make any request (including a GET requests), an options request is sent out. This options request takes ~50 - 500 ms depending on the request.
The api calls look like "https://example.com/api/v1/posts/?page=1 (2, 3, 4...etc)"
I need to wrap my head around why this request is being made, and how to improve performance for the application.
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 .
It is an OPTIONS request, using three HTTP request headers: Access-Control-Request-Method , Access-Control-Request-Headers , and the Origin header. A preflight request is automatically issued by a browser and in normal cases, front-end developers don't need to craft such requests themselves.
A CORS preflight OPTIONS request can be triggered just by adding a Content-Type header to a request — if the value's anything except application/x-www-form-urlencoded , text/plain , or multipart/form-data .
The simplest way to prevent this is to set the Content-Type to be text/plain in your case. application/x-www-form-urlencoded & multipart/form-data Content-Types are also acceptable, but you'll of course need to format your request payload appropriately.
Here's Two Strategies for Crossing Origins with Performance in Mind.
They boil down to:
Access-Control-Max-Age
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With