Home > Backend Development > Python Tutorial > How to Enable Cross-Origin Resource Sharing (CORS) in Django REST Framework using django-cors-headers?

How to Enable Cross-Origin Resource Sharing (CORS) in Django REST Framework using django-cors-headers?

Susan Sarandon
Release: 2024-11-18 08:33:02
Original
332 people have browsed it

How to Enable Cross-Origin Resource Sharing (CORS) in Django REST Framework using django-cors-headers?

Enabling CORS in Django REST Framework with django-cors-headers

Django REST Framework provides an easy way to include a RESTful API in Django applications. However, by default, Django's security settings prevent cross-origin requests. To enable cross-origin resource sharing (CORS), you can utilize the django-cors-headers third-party library.

How to Enable CORS

  1. Install django-cors-headers:
python -m pip install django-cors-headers
Copy after login
  1. Add to Installed Apps:

Edit your Django application's settings.py file and add 'corsheaders' to your INSTALLED_APPS list:

INSTALLED_APPS = (
    ...
    'corsheaders',
    ...
)
Copy after login
  1. Add Middleware:

Extend your MIDDLEWARE setting to include the CorsMiddleware from django-cors-headers:

MIDDLEWARE = [
    ...,
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...,
]
Copy after login
  1. Configure CORS Settings:

To specify the domains that are allowed to make cross-origin requests, edit the CORS_ALLOWED_ORIGINS setting:

CORS_ALLOWED_ORIGINS = [
    'http://localhost:3030',
    # Add additional allowed origins as needed
]
Copy after login
  1. Additional Settings:

Refer to the django-cors-headers documentation for a comprehensive list of CORS configuration settings, including setting custom headers, expiration times, and more.

Note: To enable CORS specifically for Django REST Framework, you can use the @action decorator with the cors_allowed_origins parameter.

The above is the detailed content of How to Enable Cross-Origin Resource Sharing (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