This article is the 24th day article of Iwate University Advent Calendar 2020.
There was a time when I created an API using Django for personal development. At that time, I encountered a CORS problem in the implementation of the API and had to deal with CORS.
Django has something called django-cors-headers. However, I tried to implement it using django-cors-headers, but I couldn't specify Access-Control-Allow-Origin
well, and I was able to send requests from other sites as well. It was.
So, I've created Django middleware and made it compatible with CORS.
I'm new to Django, so if you have any mistakes, please let me know and I'll study.
The implementation looks like this:
custom_middlewares/custom_cors_middleware.py
from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin
class CustomCorsMiddleware(MiddlewareMixin):
def process_request(self, request):
if request.method == 'OPTIONS':
response = HttpResponse()
response['Access-Control-Allow-Origin'] = 'http://localhost:3000' #Client origin
response['Access-Control-Allow-Headers'] = ', '.join([ #Add Header to allow
'Content-Type',
])
response['Access-Control-Allow-Methods'] = ', '.join([ #Added request method to allow
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
])
return response
else:
return None
def process_response(self, request, response):
response['Access-Control-Allow-Origin'] = 'http://localhost:3000' #Origin that can read the response
response['Content-Type'] = 'application/json' #Response type
return response
The process_request
method is executed when a request comes in, and if None
is the return value, the routed view
is executed.
request
↓
process_request is executed → If there is a return value, that return value is returned
↓
If the return value is None, it corresponds to request routing`view`Is executed
In the above code, in preparation for the preflight request, in the case of the OPTIONS
method, the response with the allowed origin header request method attached to the header is returned.
Then the process_response
method is executed at the end of the response.
run view
↓
process_request receives the response returned from view and processes the response
↓
response
In the above code, I often see it in CORS
Access to XMLHttpRequest at 'http://locahost:8000' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Specifies the origin from which the response can be read for, and also specifies application/json
as the response type.
All you have to do is add this custom middleware to settings.py
and you're done.
your_application_name/settings.py
MIDDLEWARE = [
'custom_middlewares.custom_cors_middleware.CustomCorsMiddleware', #add to
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
When I touched Django, I thought that there were few Japanese documents. If you can read English documents like Japanese, you may have less trouble.
Recommended Posts