𝗖𝗿𝗼𝘀𝘀-𝗢𝗿𝗶𝗴𝗶𝗻 𝗥𝗲𝘀𝗼𝘂𝗿𝗰𝗲 𝗦𝗵𝗮𝗿𝗶𝗻𝗴 (𝗖𝗢𝗥𝗦)

CORS is a security mechanism enforced by web browsers to restrict cross-origin HTTP requests.

CORS is a mechanism implemented by browsers that block websites to request data from some other URL. When a browser makes a request, it adds an origin header to the request message. If it goes to the server of the exact origin, it is allowed by the browser; if it does not, the browser blocks it. gets error like Cross-Origin Request Blocked

There are different types of requests that use CORS. For instance, the XMLHttpRequest or Fetch API both use CORS when invoked. The Web Fonts also require CORS to be enabled. If you use an image hosted on another server, it must be CORS compatible; otherwise, it will not render on the screen.

Cross-Origin Resource Sharing (CORS)

Cross-Origin Resource Sharing (CORS)

Enabling CORS in Django Rest Framework

https://pypi.org/project/django-cors-headers/3.7.0/

To handle CORS effectively in a Django Rest Framework project, we can utilize the django-cors-headers package. This package provides a middleware component that intercepts incoming HTTP requests and adds the necessary CORS headers.

A Django App that adds Cross-Origin Resource Sharing (CORS) headers to responses. This allows in-browser requests to your Django application from other origins.

Install the django-cors-headers Package:

pip install django-cors-headers==3.7.0

Add to Installed Apps

# settings.py
INSTALLED_APPS = [
    ...
    'corsheaders',
]

Add Middleware: the top of the MIDDLEWARE list

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

Configure Allowed Origins

# specify which origins are allowed
CORS_ALLOW_ALL_ORIGINS = True

# To allow all origins (not recommended for production):
CORS_ALLOW_ALL_ORIGINS = True

Ref

https://rapidapi.com/guides/cors