Problem Description
When using JavaScript for AJAX access, the following error occurred
Cause of error: JavaScript is in security consideration and is not allowed to be accessed across domains.
The following illustration is an explanation of Cross-domain access:
(Image is from the web of the "Ajax full Contact" course interception)
Because I use two IDE, one is write front-end, open is ' http://localhost:63343 ' address, the other is the Django server, opened the
' http://127.0.0.1:8000 ' address, so when ' http://localhost:63343 ' JavaScript accesses ' http://127.0.0.1:8000 ', it belongs to Cross-domain access.
When I put the front page in Django, there is no cross-domain access rejection. Solutions 1. Modify the views.py file
Modify the implementation function of the corresponding API in views.py to allow other domains to request data via Ajax:
Todo_list = [
{"id": "1", "content": "Eat"},
{"id": "2", "Content": "Eat"},
]
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 1. Install pip install django-cors-headers 2. Add App
Installed_apps = (
... ')
Corsheaders ',
...
)
3. Add Middleware
middleware = [ # Or middleware_classes on Django < 1.10
...
' Corsheaders.middleware.CorsMiddleware ',
' django.middleware.common.CommonMiddleware ',
...
]
4. Configure the address of the site to allow cross-station access
Cors_origin_whitelist = (
' localhost:63343 ',
)
5. More flexible configuration methods are written on the readme.md of the GitHub project.
Note:
settings.py files also need to be modified here
allowed_hosts = [
' localhost:63343 ',
]