django處理Ajax跨域訪問
阿新 • • 發佈:2018-12-31
問題描述
在使用javascript進行ajax訪問的時候,出現如下錯誤
出錯原因:javascript處於安全考慮,不允許跨域訪問.
下圖是對跨域訪問的解釋:
(圖片是從慕課網上的 “Ajax全接觸”課程擷取)
前端開啟的是’http://localhost:63343‘地址, 另一個是django伺服器,打開了
‘http://localhost:8000‘地址, 所以在’http://localhost:63343‘的javascript對’http://localhost:8000‘進行訪問時,埠不同,屬於跨域訪問.
當我將前端頁面放入django中後,就不會出現跨域訪問的拒絕了.
解決辦法
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的django-cors-headers專案的readme.md上有寫.
注意:
settings.py 檔案這裡也要修改
ALLOWED_HOSTS = [
'localhost:63343',
]