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
Release: 2024-11-26 10:28:11
Original
726 people have browsed it

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
Copy after login

Add it to your installed apps in settings.py:

INSTALLED_APPS = (
    ...,
    'corsheaders',
    ...,
)
Copy after login

Next, add the middleware class to your MIDDLEWARE list:

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

Finally, specify the allowed origins for CORS:

CORS_ALLOWED_ORIGINS = [
    'http://localhost:3030',
]
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template