django處理Ajax跨域訪問
使用javascript進(jìn)行ajax訪問的時(shí)候,出現(xiàn)如下錯(cuò)誤

出錯(cuò)原因:javascript處于安全考慮,不允許跨域訪問。下圖是對跨域訪問的解釋:

概念:
這里說的js跨域是指通過js或python在不同的域之間進(jìn)行數(shù)據(jù)傳輸或通信,比如用ajax向一個(gè)不同的域請求數(shù)據(jù),或者通過js獲取頁面中不同域的框架中(Django)的數(shù)據(jù)。只要協(xié)議、域名、端口有任何一個(gè)不同,都被當(dāng)作是不同的域。
解決辦法
1. 修改views.py文件
修改views.py中對應(yīng)API的實(shí)現(xiàn)函數(shù),允許其他域通過Ajax請求數(shù)據(jù):
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
2.1. 安裝 pip install django-cors-headers
2。2 添加app
INSTALLED_APPS = ( ... 'corsheaders', ...)
2.3 添加中間件
MIDDLEWARE = [ # Or MIDDLEWARE_CLASSES on Django < 1.10 ... 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ...]
2.4 配置允許跨站訪問本站的地址
CORS_ORIGIN_ALLOW_ALL = FalseCORS_ORIGIN_WHITELIST = ( 'localhost:63343',)# 默認(rèn)值是全部:CORS_ORIGIN_WHITELIST = () # 或者定義允許的匹配路徑正則表達(dá)式.CORS_ORIGIN_REGEX_WHITELIST = ('^(https?://)?(/w+.)?>google.com$', ) # 默認(rèn)值:CORS_ORIGIN_REGEX_WHITELIST = ()2.5 設(shè)置允許訪問的方法
CORS_ALLOW_METHODS = ('GET','POST','PUT','PATCH','DELETE','OPTIONS')
新聞熱點(diǎn)
疑難解答
圖片精選