Django Rest Framework / Angular Request JS Pre-Validation Options

I wrote an API using the Django Rest Framework. For authentication, I use django-oauth2-provider: https://github.com/caffeinehit/django-oauth2-provider

I have the settings configured on my settings page like this (using the 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 using Angular JS. However, every time we make any request (including GET requests), a parameter request is sent. This request for parameters takes ~ 50 - 500 ms depending on the request.

The api calls look like this: https://example.com/api/v1/posts/?page=1 (2, 3, 4 ... etc.) "

I need to wrap my head around why this request is being executed, and how to improve performance for the application.

+6
source share
4 answers

Here are two strategies for intersecting sources with performance in mind .

They come down to:

  • Proper Use of Access-Control-Max-Age
  • Staying under a “simple request”
+1
source

Use the CORS_PREFLIGHT_MAX_AGE parameter to cache responses:

CORS_PREFLIGHT_MAX_AGE: specify the number of seconds during which the client / browser can cache the response to pre-flight display

This guide describes Access-Control-Max-Age :

Access-Control-Max-Age (optional). Performing a pre-flight request for each request becomes expensive because the browser makes two requests for each client request. The value of this header allows a preflight response to be cached for a specified number of seconds.

+1
source

when your request for your server’s pre-flight request should resolve this request, responding back with appropriate headers, the shoud server sent a request using the Access-Control-Allow-Origin set to Content-Type will solve your problem.

0
source

This is caused by the browser from which the request was made. Since I control both the server instance and the client, in my case I was able to set the request headers on the client to "text / plain", which fulfills the requirements of CORS pre-flight control. Then, on the server side, I changed my rest_framework source to basically accept "text / plain" as the JSON media type. A simple workaround, however, may not be acceptable to everyone.

0
source

Source: https://habr.com/ru/post/973617/


All Articles