This article mainly introduces the Django cross-domain request processing sample code, has a certain reference value, now share to everyone, the need for friends can refer to
Django handles Ajax cross-domain access
When using JavaScript for AJAX access, the following error occurs
Cause of error: JavaScript is safe and does not allow cross-domain access. is an explanation of cross-domain access:
Concept:
The JS cross-domain refers to the data transfer or communication between different domains via JS or python, such as using AJAX to request data from a different domain, or by JS to get the frames of the different domains (Django) in the page. As long as the protocol, domain name, and port are any different, are considered to be different domains.
Solutions
1. Modify the views.py file
Modify the implementation function of the corresponding API in views.py, allowing other domains to request data via Ajax:
Todo_list = [ {"id": "1", "Content": "Meal"}, {"id": "2", "Content": "Eat"},]class Query: @staticmethod C3/>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 "] = "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 adding apps
Installed_apps = (... ') Corsheaders ', ...)
2.3 Adding middleware
middleware = [# Or middleware_classes on Django < 1.10 ... ' Corsheaders.middleware.CorsMiddleware ', ' django.middleware.common.CommonMiddleware ', ...]
2.4 Configuration allows cross-site access to the address of the site
Cors_origin_allow_all = Falsecors_origin_whitelist = ( ' localhost:63343 ',) # The default value is all: Cors_origin_whitelist = () # Or define the allowed match path regular expression. Cors_origin_regex_whitelist = (' ^ (https?:/ /)? (\w+.)? >google.com$ ',) # default value: Cors_origin_regex_whitelist = ()
2.5 Setting the method to allow access
Cors_allow_methods = (' GET ', ' POST ', ' PUT ', ' PATCH ', ' DELETE ', ' OPTIONS ')
2.6 Set the allowed headers:
Default value:
Cors_allow_headers = (' X-requested-with ', ' content-type ', ' accept ', ' origin ', ' authorization ', ' X-csrftoken ')