同源策略与 JSONP CORS

同源策略与 JSONP CORS

同源策略

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

所谓同源是指,域名,协议,端口相同。如果非同源,那么在请求数据时,浏览器会在控制台中报一个异常,提示拒绝访问。

示例

client:http://127.0.0.1:8000

<!-- 前端页面 -->
<!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://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>

<script>
    $(".get_service").click(function () {
        $.ajax({
            url: "http://127.0.0.1:8001/service/",
            success: function (data) {
                console.log(data);
            }
        });
    });

</script>
</body>
</html>
# views.py
def index(request):
    return render(request, "index.html")

service:http://127.0.0.1:8001

# views.py
def service(request):
    info = {"name": "egon", "age": 34, "price": 200}
    return HttpResponse(json.dumps(info))

当在 client 上按下按钮,会报如下错误 (在火狐浏览器中查看) :

firefox1

此时查看 service 端,发现请求已经发生,是浏览器对非同源请求返回的结果做了拦截。

JSONP

JSONP 是 JSON 用来跨域的一个东西。原理是通过 script 标签的跨域特性来绕过同源策略。

JSONP 的原型:创建一个回调函数,然后在远程服务上调用这个函数并且将 JSON 数据形式作为参数传递,完成回调。将 JSON 数据填充进回调函数,这就是 JSONP 的 JSON+Padding 的含义。

客户端

客户端在 AJAX 发送数据的时候改变其 dataType 属性的值为 jsonp ,并增加一个属性 jsonp: "callbacks" 即可。

$(".get_service").click(function () {
	$.ajax({
		url: "http://127.0.0.1:8001/service/",
		type: "get",
		dataType: "jsonp",    // 伪造ajax  基于script
		jsonp: "callbacks",
		success: function (data) {
			console.log(data);
		}
	});
});

服务端

服务端的视图函数中将所需数据以回调函数的形式返回:

def service(request):
	info = {"name": "egon", "age": 34, "price": 200}
	func = request.GET.get("callbacks")
	return HttpResponse("%s('%s')" % (func, json.dumps(info)))

CORS

CORS 是最常用的方式,其方法比 JSONP 简单,客户端无需改动,只需在服务端加上 response["Access-Control-Allow-Origin"] 头就行。其值赋值为允许访问的源,即地址和端口号,如果赋值为 "*" ,代表所有源都可访问。

def service(request):
    info = {"name": "egon", "age": 34, "price": 200}
    response = HttpResponse(json.dumps(info))
    response["Access-Control-Allow-Origin"] = "*"
    return response

一个 JSONP 的应用

通过一个接口得到以 JSONP 回调函数形式的数据,对其进行整理得到一周内每天的节目列表。


    // 实例应用
    $(".get_service").click(function () {
        $.ajax({
            url: "http://www.jxntv.cn/data/jmd-jxtv2.html",
            type: "get",
            dataType: "jsonp",    // 伪造ajax  基于script
            jsonp: "callbacks",
            jsonpCallback: "list",
            success: function (data) {
                {#console.log(data.data);#}

                var html = '';
                $.each(data.data, function (index, weekday) {
                    html += '<p>'+ weekday.week +'</p>';
                    $.each(weekday.list, function (j, show) {
                        html += '<p><label>'+ show.time +'</label>&nbsp;&nbsp;<a href='+ show.link +'>'+ show.name +'</a></p>';
                    });
                });

                $("body").append(html);
            }
        });
    });

GitHub 地址:https://github.com/protea-ban/oldboy/tree/master/9day85

posted @ 2018-11-01 19:05  banshaohuan  阅读(130)  评论(0编辑  收藏  举报