1、什么是跨域?
就是由於域名不同,或者端口不同,或者協議不同瀏覽器的同源策略就會自動將不同源的請求進行阻攔。形成跨域。
2、什么是簡單請求?
HTTP方法是下列方法之一
HEAD, GET,POST
HTTP頭信息不超出以下幾種字段
Accept, Accept-Language, Content-Language, Last-Event-ID
Content-Type只能是下列類型中的一個
application/x-www-from-urlencoded
multipart/form-data
text/plain
任何一個不滿足上述要求的請求,即會被認為是復雜請求~~
復雜請求會先發出一個預請求,我們也叫預檢,OPTIONS請求~~
2、解決方法
方法一:jsonp
通過jsonp不阻止src請求入手實現

class Test(APIView): def get(self, request): callback = request.query_params.get("callback", "") ret = callback + "(" + "'success'" + ")" return HttpResponse(ret)

<button id="btn_one">點擊我向JsonP1發送請求</button> <script> // 測試發送請求失敗 跨域不能得到數據 $('#btn_one').click(function () { $.ajax({ url: "http://127.0.0.1:8000/jsonp1", type: "get", success: function (response) { console.log(response) } }) }); function handlerResponse(response) { alert(response) }; window.onload = function () { $("#btn_one").click(function () { let script_ele = document.createElement("script"); script_ele.src = "http://127.0.0.1:8000/jsonp1?callback=handlerResponse"; document.body.insertBefore(script_ele, document.body.firstChild); }) } </script>
方法二:添加響應頭
寫一個中間件,將瀏覽器拒絕的都讓他允許就好。
<button id="my_button">點我你將有意想不到的收獲</button> <script> $("#my_button").click(function () { $.ajax({ url:"http://127.0.0.1:8000/cors/my_cors/", type:"put", # 復雜請求的請求方法,需要中間件中允許Methods contentType:"application/json", # 配置了ContentType,中間件中要寫相應的命令允許 success:function (data) { console.log(data) } }) }) </script>

from django.utils.deprecation import MiddlewareMixin class MyCors(MiddlewareMixin): def process_response(self, request, response): # 寫了這條命令后,默認允許所有 response["Access-Control-Allow-Origin"] = "*" # 如果是復雜請求,就會先發送一個OPTIONS進行預檢測 if request.method == "OPTIONS": # 當AJAX 請求中如果設置了ContentType,就需要在中間件中寫這條允許Content-Type response["Access-Control-Allow-Headers"] = "Content-Type" # 如果是put,patch,delete 等請求方式,需要先配置以下命令 response["Access-Control-Allow-Methods"] = "PUT,PATCH,DELETE" return response
然后在settings的中間件中注冊該中間件
方法三:通過django-cors-headers