在使用javascript进行ajax访问的时候,出现如下错误
出错原因:javascript处于安全考虑,不允许跨域访问.
下图是对跨域访问的解释:
(图片是从慕课网上的 “Ajax全接触”课程截取)
前端打开的是’http://localhost:63343‘地址, 另一个是django服务器,打开了
‘http://localhost:8000‘地址, 所以在’http://localhost:63343‘的javascript对’http://localhost:8000‘进行访问时,端口不同,属于跨域访问.
当我将前端页面放入django中后,就不会出现跨域访问的拒绝了.
修改views.py中对应API的实现函数,允许其他域通过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()
django-cors-headers
GitHub地址: https://github.com/ottoyiu/django-cors-headers
pip install django-cors-headers
INSTALLED_APPS = (
...
'corsheaders',
...
)
MIDDLEWARE = [ # Or MIDDLEWARE_CLASSES on Django < 1.10
...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
]
CORS_ORIGIN_WHITELIST = (
'localhost:63343',
)
settings.py 文件这里也要修改
ALLOWED_HOSTS = [
'localhost:63343',
]