How can I enable CORS on Django REST Framework

2020-01-22 18:14发布

How can I enable CORS on my Django REST Framework? the reference doesn't help much, it says that I can do by a middleware, but how can I do that?

8条回答
\"骚年 ilove
2楼-- · 2020-01-22 18:52

Below are the working steps without the need for any external modules:

Step 1: Create a module in your app.

E.g, lets assume we have an app called user_registration_app. Explore user_registration_app and create a new file.

Lets call this as custom_cors_middleware.py

Paste the below Class definition:

class CustomCorsMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        # One-time configuration and initialization.

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.

        response = self.get_response(request)
        response["Access-Control-Allow-Origin"] = "*"
        response["Access-Control-Allow-Headers"] = "*"

        # Code to be executed for each request/response after
        # the view is called.

        return response

Step 2: Register a middleware

In your projects settings.py file, add this line

'user_registration_app.custom_cors_middleware.CustomCorsMiddleware'

E.g:

  MIDDLEWARE = [
        'user_registration_app.custom_cors_middleware.CustomCorsMiddleware', # ADD THIS LINE BEFORE CommonMiddleware
         ...
        'django.middleware.common.CommonMiddleware',

    ]

Remember to replace user_registration_app with the name of your app where you have created your custom_cors_middleware.py module.

You can now verify it will add the required response headers to all the views in the project!

查看更多
来,给爷笑一个
3楼-- · 2020-01-22 18:58

After installing django-cors-headers and adding it to your middlewares, you may also need to migrate in order for the CorsModel model to be created in your DB. I was getting exceptions while trying to flush it otherwise.

python3 manage.py makemigrations corsheaders
python3 manage.py migrate
查看更多
登录 后发表回答