Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework/Angular JS Preflight options request

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.

like image 298
Lfa Avatar asked Aug 10 '14 19:08

Lfa


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 .

What is preflight request in angular?

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.

How do I enable preflight requests?

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 .

How do you skip a preflight request in react?

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.


1 Answers

Here's Two Strategies for Crossing Origins with Performance in Mind.

They boil down to:

  1. Proper use of Access-Control-Max-Age
  2. Staying within the confines of a "simple request"
like image 150
nikmd23 Avatar answered Oct 11 '22 14:10

nikmd23