How to handle Cross-Origin Resource Sharing (CORS) in Django?

There are typically two methods for handling cross-origin resource sharing issues in Django.

  1. Allow cross-origin resource sharing in Django by using the django-cors-headers package.
  2. Headers for enabling CORS in Django.
  3. configuration file

Firstly, you need to install django-cors-headers.

pip install django-cors-headers

Then configure the middleware in settings.py.

INSTALLED_APPS = [
    ...
    'corsheaders',
]

MIDDLEWARE = [
    ...
    'corsheaders.middleware.CorsMiddleware',
]

CORS_ORIGIN_ALLOW_ALL = True
  1. Allow-Origin Access-Control
from django.http import JsonResponse

def my_view(request):
    response = JsonResponse({'message': 'Hello, World!'})
    response['Access-Control-Allow-Origin'] = '*'
    response['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS'
    response['Access-Control-Allow-Headers'] = 'Content-Type'
    return response

This way, you can now handle cross-origin resource sharing issues in Django.

广告
Closing in 10 seconds
bannerAds