同源策略和Jsonp

一、同源策略

  同源策略(Same origin policy)是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响。可以说Web是构建在同源策略基础之上的,浏览器只是针对同源策略的一种实现。

  同源策略,它是由 Netscape提出的一个著名的 安全策略。现在所有支持JavaScript 的浏览器都会使用这个策略。所谓 同源是指,域名,协议,端口相同当一个浏览器的两个tab页中分别打开来 百度和谷歌的页面当浏览器的百度tab页执行一个脚本的时候会检查这个脚本是属于哪个页面的,即检查是否同源,只有和百度同源的脚本才会被执行。如果非同源,那么在请求数据时,浏览器会在控制台中报一个异常,提示拒绝访问

跨域示例

端口8006:点击按钮跨域访问

############# urls #############
from django.contrib import admin
from django.urls import path
from app01 import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('index/', views.index),
    path('service/', views.service),
]

############# 视图 #############
from django.shortcuts import render, HttpResponse
# Create your views here.

def index(request):
    return render(request, "index.html")

def service(request):
    return HttpResponse("技师alex")

############# index.html #############
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h3>INDEX</h3>
<button class="get_service">洗剪吹</button>

<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script>
    $(".get_service").click(function () {
        $.ajax({
             // url: "/service/",
            url: "http://127.0.0.1:8008/service/",   // 跨域访问
            success:function(data){
                console.log(data);
            }
        })
    })
</script>
</body>
</html>

端口8008:点击按钮同域访问

############# urls #############
from django.contrib import admin
from django.urls import path
from app01 import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('index/', views.index),
    path('service/', views.service),
]

############# 视图 #############
from django.shortcuts import render, HttpResponse
# Create your views here.

def index(request):
    return render(request, "index.html")

def service(request):
    print("技师egon")
    return HttpResponse("技师alex")

############# index.html #############
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h3>INDEX</h3>
<button class="get_service">洗剪吹</button>

<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script>
    $(".get_service").click(function () {
        $.ajax({
             url: "/service/",
            success:function(data){
                console.log(data);
            }
        })
    })
</script>
</body>
</html>

测试验证:

(1)跨域访问报错

(2)同域访问正常

(3)跨域访问虽然被拦截了,但是目标服务视图函数有执行打印。说明跨域时,请求可以发送过去,但是返回给浏览器时被拦截。

  

  项目2中的访问已经发生了,说明是浏览器对非同源请求返回的结果做了拦截。

 

猜你喜欢

转载自www.cnblogs.com/xiugeng/p/9484923.html