最新消息:

Django处理Ajax跨域访问[zz]

未分类 王杭州 3619浏览 0评论 [编辑]

在使用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]

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址