1. 程式人生 > >跨域(my)

跨域(my)

CORS跨域請求

CORS即Cross Origin Resource Sharing 跨域資源共享,

那麼跨域請求還分為兩種,一種叫簡單請求,一種是複雜請求~~

簡單請求

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請求~~

瀏覽器的同源策略

跨域是因為瀏覽器的同源策略導致的,也就是說瀏覽器會阻止非同源的請求~

那什麼是非同源呢~~即域名不同,埠不同都屬於非同源的~~~

瀏覽器只阻止表單以及ajax請求,並不會阻止src請求,所以我們的cnd,圖片等src請求都可以發~~

Ajax跨域現象

urls.py:

 

from django.conf.urls import url
from django.contrib import admin
from .views import jsonp1 urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^jsonp1',jsonp1) ]
View Code

 

views.py

from django.http import HttpResponse

def jsonp1(request):
    return HttpResponse("hello")
View Code

建立 .html 當做前端:

<!DOCTYPE html>
<html lang="
en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script> <body> <button id="btn">點我向後端傳送資料</button> <script> $("#btn").click(function(){ $.ajax({ url:"http://127.0.0.1:8000/jsonP1" , //後端的路由地址 success:function(data){ console.log(data) } }) }) </script> </body> </html>
jsonp2

 

 

解決跨域

JSONP

jsonp的實現原理是根據瀏覽器不阻止src請求入手~來實現的~~

urls.py:

from django.conf.urls import url
from django.contrib import admin
from .views import jsonp1

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^jsonp1',jsonp1)
]
View Code

views.py:

from django.http import HttpResponse

def jsonp1(request):

    ret = "handlerResponse('hello555')"
    return HttpResponse(ret)
View Code

jsonp2.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<body>
<button id="btn">點我向後端傳送資料</button>
<script>



   // 頁面載入完成執行的方法
    window.onload = function () {
        let ele = document.createElement("script");
        // 給標籤加src屬性
        ele.src = "http://127.0.0.1:8001/jsonp1";
        // 把標籤放到頁面上
         document.body.insertBefore(ele, null)
    }

    function handlerResponse(data) {
        alert(data)
    }
</script>
</body>
</html>
View Code

===========================

views.py:

from django.http import HttpResponse

def jsonp1(request):
    callback = request.GET.get("callback","")#獲取callback

    # ret = "handlerResponse('hello555')"
    ret = callback + "('hello')"
    return HttpResponse(ret)
View Code

jsonp2.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<body>
<button id="btn">點我向後端傳送資料</button>
<script>


    function handlerResponse(data) {
        alert(data)
    }
   // 頁面載入完成執行的方法
    window.onload = function () {
        let ele = document.createElement("script");
        // 給標籤加src屬性
        ele.src = "http://127.0.0.1:8001/jsonp1?callback=handlerResponse";
        // 把標籤放到頁面上
         document.body.insertBefore(ele, null)
    }


</script>
</body>
</html>
View Code

新增響應頭

settings.py註釋中介軟體csrf

註冊中介軟體:'middlewares.MyCors'

 urls.py:

from django.conf.urls import url
from django.contrib import admin
from .views import jsonp1

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^jsonp1',jsonp1)
]
View Code

 

jsonp2.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<body>
<button id="btn">點我向後端傳送資料</button>
<script>



    $("#btn").click(function () {
        $.ajax({
            url: "http://127.0.0.1:8001/jsonp1",
            type: "post",
            contentType: "application/json",
            data: {"name": "liangshuang"},
            success: function (data) {
                console.log(data)
            }
        })
    })








</script>
</body>
</html>
View Code

views.py

from django.http import HttpResponse

def jsonp1(request):
    callback = request.GET.get("callback","")#獲取callback

    # ret = "handlerResponse('hello555')"
    ret = callback + "('hello')"
    print(ret)
    return HttpResponse(ret)
View Code

在專案下建立middlewares.py定義中介軟體

# -*- coding: utf-8 -*-
# __author__ = "maple"
from django.middleware.security import SecurityMiddleware
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":
            response["Access-Control-Allow-Headers"] = "Content-Type"
            response["Access-Control-Allow-Methods"] = "POST, PUT, PATCH, DELETE"
        return response
View Code