1.安装:pip install django-cors-headers
2.修改django项目中的settings.py
INSTALLED_APPS = [ ... 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', # 这个是跨域的中间件需要放在最上边,也可以在下边两个的下面,但是不能放在其他位置了 'django.middleware.common.CommonMiddleware', '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', 'XXX.middleware.MyCorsMiddle.MyCorsMiddle', # 这是自己写的中间件,添加响应头 ] # 新添以下内容 CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW_ALL = True # CORS_ORIGIN_WHITELIST = (‘*’) CORS_ALLOW_METHODS = ( 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', 'VIEW', ) CORS_ALLOW_HEADERS = ( 'XMLHttpRequest', 'X_FILENAME', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', )
3.添加中间件来添加响应头
就是为了在响应头内添加上Access-Control-Allow-Origin = *
from django.utils.deprecation import MiddlewareMixin class MyCorsMiddle(MiddlewareMixin): def process_response(self, request, response): if request.method == 'OPTIONS': # 允许它 response['Access-Control-Allow-Headers'] = 'Content-Type' # obj['Access-Control-Allow-Headers']='*' # obj['Access-Control-Allow-Origin']='http://127.0.0.1:8000' response['Access-Control-Allow-Origin'] = '*' return response
开发过程中遇到的问题,有误斧正。