I'm trying to add django-cors-headers to my django rest API to add the HTTP header Access-Control-Allow-Origin
in the response object, but I have not managed to make it work. I have followed the instructions in the official documentation but I can not get it to work.
settings.py
file: ... INSTALLED_APPS = [ 'suit', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'hvad', 'rest_framework.authtoken', 'rest_framework_swagger', 'accounts.apps.AccountsConfig', 'rest_auth', ] ... MIDDLEWARE:[ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] ... # CORS Config CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = False
If you are Using Chrome, Use https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en
================================================================================
CORS_URLS_REGEX = r'^/*$'
CORS_ALLOW_METHODS
A list of HTTP verbs that are allowed for the actual request. Defaults to:
CORS_ALLOW_METHODS = (
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
)
CORS_ALLOW_HEADERS = (
'accept',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
)
django-cors-headers
is reasonably fool-proof and your configuration seems correct to me.
There is however a gotcha I've had issues with too:
If you configure your server to serve static files without invoking Django / Python (pretty common, even on the built-in server), django-cors-headers
cannot apply a CORS header to those responses.
Depending on the browser, this will cause problems with asynchronous requests, fonts and sometimes even images, video and audio.
Finally, It works only when I create a new middleware file, here's the content of my middleware.
1- Put this file under <your_app>/middleware/cors.py
2- Edit your setting.py to add the new middleware
# -*- coding:utf-8 -*-
from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin
class CorsMiddleware(MiddlewareMixin):
def process_response(self, request, response):
response["Acces-Control-Allow-Origin"] = "*"
return response
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.