在使用javascript进行ajax访问的时候,出现如下错误
No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://x.x.x.x’ is therefore not allowed access.
出错原因:javascript处于安全考虑,不允许跨域访问.
下图是对跨域访问的解释:
解决办法
1. 修改views.py文件
修改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()
2. 添加中间件 django-cors-headers
GitHub地址: https://github.com/ottoyiu/django-cors-headers
1. 安装 pip install django-cors-headers
2. 添加app
INSTALLED_APPS = (
…
‘corsheaders’,
…
)
3. 添加中间件
MIDDLEWARE = [ # Or MIDDLEWARE_CLASSES on Django < 1.10
...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
]
4. 配置允许跨站访问本站的地址
CORS_ORIGIN_WHITELIST = (
‘localhost:63343′,
)
5. 更多更灵活的配置方式在github项目的readme.md上有写.
注意:
settings.py 文件这里也要修改
ALLOWED_HOSTS = [
'localhost:63343',
]
原文地址:http://blog.csdn.net/qq_27068845/article/details/73007155
转载请注明:王杭州的个人网页 » Django处理Ajax跨域访问[zz]