1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| 简单请求,在响应头中加入 "Access-Control-Allow-Origin":"*" headers={"Access-Control-Allow-Origin": "*"} 非简单请求,需要增加判断,如果是OPTIONS请求,在请求头中加入允许
from django.utils.deprecation import MiddlewareMixin class CorsMiddleWare(MiddlewareMixin): def process_response(self,request,response): if request.method=="OPTIONS": response["Access-Control-Allow-Headers"]="Content-Type" response["Access-Control-Allow-Origin"] = "*" return response
pip install django-cors-headers
INSTALLED_APPS = [ ... 'corsheaders', ... ]
MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', ... ]
CORS_ALLOW_ALL_ORIGINS = True 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', 'Pragma', )
|