Home >Backend Development >Python Tutorial >How Do I Enable CORS in Django REST Framework Using django-cors-headers?

How Do I Enable CORS in Django REST Framework Using django-cors-headers?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-26 10:28:11735browse

How Do I Enable CORS in Django REST Framework Using django-cors-headers?

Enabling CORS on Django REST Framework

Enabling CORS (Cross-Origin Resource Sharing) on Django REST Framework allows clients to make cross-domain requests to your API. While the Django documentation briefly mentions using middleware for this purpose, it lacks specific implementation details.

Solution Using Middleware

As suggested, you can enable CORS using the django-cors-headers library:

python -m pip install django-cors-headers

Add it to your installed apps in settings.py:

INSTALLED_APPS = (
    ...,
    'corsheaders',
    ...,
)

Next, add the middleware class to your MIDDLEWARE list:

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

Finally, specify the allowed origins for CORS:

CORS_ALLOWED_ORIGINS = [
    'http://localhost:3030',
]

Additional Configuration

Visit the django-cors-headers documentation for advanced configuration options and CORS settings, such as:

  • CORS_ORIGIN_ALLOW_ALL
  • CORS_ORIGIN_ALLOW_CREDENTIALS
  • CORS_ALLOW_METHODS
  • CORS_ALLOW_HEADERS

Consult the documentation for further customization based on your specific requirements.

The above is the detailed content of How Do I Enable CORS in Django REST Framework Using django-cors-headers?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn