Home >Backend Development >Python Tutorial >Sample code for Django cross-domain request handling
This article mainly introduces the sample code about Django cross-domain request processing, which has certain reference value. Now I share it with you. Friends in need can refer to it
django handles Ajax cross-domain requests Domain access
When using javascript for ajax access, the following error occurs
Cause of error: JavaScript is for security reasons and cross-domain access is not allowed . The following figure is an explanation of cross-domain access:
Concept:
The js cross-domain mentioned here refers to the js or Python performs data transmission or communication between different domains, such as using ajax to request data from a different domain, or using js to obtain data in the framework (Django) of different domains in the page. As long as the protocol, domain name, or port are any different, they are regarded as different domains.
Solution
1. Modify the views.py file
Modify the corresponding API implementation function in views.py, Allow other domains to request data through Ajax:
todo_list = [ {"id": "1", "content": "吃饭"}, {"id": "2", "content": "吃饭"}, ] class Query(View): @staticmethod def get(request): response = JsonResponse(todo_list, safe=False) response["Access-Control-Allow-Origin"] = "*" response["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS" response["Access-Control-Max-Age"] = "1000" response["Access-Control-Allow-Headers"] = "*" return response @staticmethod def post(request): print(request.POST) return HttpResponse()
2. Add middleware django-cors-headers
GitHub address: https:// github.com/ottoyiu/django-cors-headers
2.1. Install pip install django-cors-headers
2. 2 Add app
INSTALLED_APPS = ( ... 'corsheaders', ... )
2.3 Add middleware
MIDDLEWARE = [ # Or MIDDLEWARE_CLASSES on Django < 1.10 ... 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ]
2.4 Configure the address that allows cross-site access to this site
CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = ( 'localhost:63343', ) # 默认值是全部: CORS_ORIGIN_WHITELIST = () # 或者定义允许的匹配路径正则表达式. CORS_ORIGIN_REGEX_WHITELIST = ('^(https?://)?(\w+.)?>google.com$', ) # 默认值: CORS_ORIGIN_REGEX_WHITELIST = ()
2.5 Set the allowed access method
CORS_ALLOW_METHODS = ( 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS' )
2.6 Set the allowed header:
Default value:
CORS_ALLOW_HEADERS = ( 'x-requested-with', 'content-type', 'accept', 'origin', 'authorization', 'x-csrftoken' )
Related recommendations:
Django examples of using logging to print logs
Django Project Practical User Avatar Uploading and Access
The above is the detailed content of Sample code for Django cross-domain request handling. For more information, please follow other related articles on the PHP Chinese website!