Cross-Origin Resource Sharing In Django Rest API

Osirus Djodji
2 min readMar 8, 2022

Cross-origin resource sharing (CORS) is a mechanism that consists of adding HTTP headers to allow a user agent to access resources of a server located on another origin than the current site. A user agent makes a multi-origin HTTP request (cross-origin) when it requests a resource coming from a domain, a protocol or a port different from those used for the current page.

CORS helps support secure cross-origin requests and data transfers between browsers and web servers. Recent browsers use CORS in a containing API like XMLHttpRequest or Fetch to help reduce the risk of cross-origin HTTP requests.

The best way to deal with CORS in REST framework is to add the required response headers in middleware. This ensures that CORS is supported transparently, without having to change any behavior in your views.

In Django Rest Framework, you can manage CORS with django-cors-headers. Just get in your project virtual environment and do:

$ pip install django-cors-headers

and add it to your installed apps:

INSTALLED_APPS = [...,"corsheaders",...,]

Next, be sure to add a middleware class to listen for responses:

MIDDLEWARE = [...,"corsheaders.middleware.CorsMiddleware","django.middleware.common.CommonMiddleware",...,]

You’d better add this middleware on top so it will be able to add CORS to all responses.

Then you just need to set a value in your settings for CORS.

CORS_ALLOWED_ORIGINS = ["https://example.com","https://sub.example.com","http://localhost:8080","http://127.0.0.1:9000",]

or just:

CORS_ORIGIN_ALLOW_ALL = True

--

--