python Josnp(跨域)

python Josnp(跨域)

所谓的跨域就是进行不用域名内的请求,好比如说我在A域名想访问B域名的内容就是一种跨域的行为。

但是在我们浏览器端会有一个同源策略的设置,这个同源策略只对Ajax请求有限制,如果你通过Ajax请求发送数据,在被访问的一端能够接受访问请求并且进行处理后返回给浏览器,但是浏览器不进行接收,所以不能进行跨域请求。

我们机智的人类想到了一个方法可以解决这个同源策略的问题,他们采用的方法是:
    我们知道浏览器会对Ajax请求进行同源策略但是对带有src功能的标签没有进行限制,我们就可以设置通过带有src的标签去访问其他域名的内容

一、设置本地配置和Django配置文件

1、设置本机的C:WindowsSystem32driversetc路径下的域名   

# Copyright (c) 1993-2009 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
#
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
#
# For example:
#
# 102.54.94.97 rhino.acme.com # source server
# 38.25.63.10 x.acme.com # x client host

# localhost name resolution is handled within DNS itself.
#	127.0.0.1 localhost
#	::1 localhost
127.0.0.1	www.s4.com 
127.0.0.1	www.s5.com

2、设置Django配置文件的内容

ALLOWED_HOSTS = ['www.s4.com',]

二、JOSNP(自动动态生成标签)

1.JOSNP自动动态生成带有src的标签(html)(通过带有src的标签进行访问)

==============================================通过src进行访问 html=========================================
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{#这个是josnp采用的方式   要求客户端和服务端进行约束 自己动态创建标签#}
function getUsers() {
{#定义一个点击函数#}
    var tag =document.createElement('script');
{#创建一个script标签,name=tag#}
    tag.src='http://www.s4.com:8010/users/?callback=bbb';
{#通过tag.src设置访问路劲,这个是get请求把数据放在url上#}
{#    tag.src='http://www.s4.com:8010/users/?funcname=bbb';#}
    document.head.appendChild(tag);
{#在把名字等于tag的标签添加到请求头中#}
}
</script>
</body>
</html>

  

2、JOSNP自动动态生成带有src的标签(views)

from django.shortcuts import render,redirect,HttpResponse
import json
# Create your views here.

def users(request):
    v =request.GET.get('callback')
    # v =request.GET.get('funcname')
    print('请求来了')
    user_list=[
        'alex','eric','egon'
    ]
    user_list_str=json.dumps(user_list)
    temp ='%s(%s)' %(v,user_list_str)
    print(temp)
    return HttpResponse(temp)

三、JOSNP(JQuery)

1、JOSNP 通过JQuery本身的方式访问(html)

====================================通过JQuery访问 html===================================================
<!DOCTYPE html
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{#通过JQuery进行跨域请求,只要遵循JQuery标准就能成功访问#}
function getUsers() {
{#定义一个点击函数#}
    $.ajax({
{#通过Ajax 向http://www.s4.com:8010/users/发送请求#}
        url: 'http://www.s4.com:8010/users/',
        type: 'POST',
{#发送方式#}
        dataType: 'JSONP',
{#设置JSONP模式#}
        jsonp: 'funcname',
{#Jsonp的值是funcname#}
        jsonpCallback: 'bbb'
{#设置后台的函数名#}
    })

function bbb(arg) {
    console.log(arg)
}

</script>
</body>
</html>

2、JOSNP 通过JQuery本身的方式访问(views)

from django.shortcuts import render,redirect,HttpResponse
import json
# Create your views here.

def users(request):
    v =request.GET.get('callback')
    # v =request.GET.get('funcname')
    print('请求来了')
    user_list=[
        'alex','eric','egon'
    ]
    user_list_str=json.dumps(user_list)
    temp ='%s(%s)' %(v,user_list_str)
    print(temp)
    return HttpResponse(temp)

四、CORS(一种不需要通过别的方式去访问其他域名的方式)

cors 的原理是访问其他域名的内容,在执行完成后返回给浏览器时,告知浏览器不对Ajax请求进行同源限制

1、cors简单访问(html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <input type="button" value="获取用户列表" onclick="getUsers()">
<ul id="user_list"></ul>
<script src="/static/jquery-3.2.1.js"></script>
<script>
    function getUsers() {
        $.ajax({
            url:'http://www.s4.com:8010/lsd_users/',
            type:'GET',
            success:function (arg) {
                console.log(arg)
            }
        })
    }
</script>
</body>
</html>

2、cors简单的访问(views)

在访问其他域名的内容并执行完成后,返回一个响应头,响应头内有告知浏览器不进行Ajax的同源策略的方法。

from django.shortcuts import render,redirect,HttpResponse
import json
# Create your views here.def lsd_users(request):
    user_list = [
        'alex', 'eric', 'egon'
    ]
    print('请求来了!')
    user_list_str=json.dumps(user_list)
    obj=HttpResponse(user_list_str)
    obj['Access-Control-Allow-Origin']="http://www.s5.com:8100"
    #  反会给浏览器已给响应头,告诉浏览器这个API不执行同源策略
    return obj

3、cors复杂的访问(html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <input type="button" value="获取用户列表" onclick="getUsers()">
<ul id="user_list"></ul>
<script src="/static/jquery-3.2.1.js"></script>
<script>
    function getUsers() {
        $.ajax({
            url:'http://www.s4.com:8010/new_users/',
            type:'DELETE',

            success:function (arg) {
                console.log(arg)
            }
        })
    }
</script>
</body>
</html>

4、cors复杂的访问(views)

复杂的访问请求要先进行一个预检,看下什么样的请求方式和请求域名可以进行访问,返回给浏览器浏览器在判断是不是和预检的需求一致,如果一致就可以访问,再次返回给浏览器时设置响应头,响应头内有告知浏览器不进行Ajax的同源策略的方法。

from django.shortcuts import render,redirect,HttpResponse
import json
# Create your views here
def new_users(request):
    print(request.method)
    # 打印请求方式
    user_list = [
        'alex', 'eric', 'egon'
    ]
    if request.method=='OPTIONS':
        # 判断请方式是不是一种options请求
        print('预检....')
        obj=HttpResponse()
        obj['Access-Control-Allow-Origin']='*'
        # 所有域名的都可以进行访问
        obj['Access-Control-Allow-Methods']='DELETE'
        # 返回请求的方式,并告知浏览器不进行同源策略
        return obj
    obj = HttpResponse('asdfasdf')
    # 再次请求来的时候返回内容
    obj['Access-Control-Allow-Origin'] = "*"
    # 允许所有的域名进行访问
    return obj
 
 
 
原文地址:https://www.cnblogs.com/jiadi321/p/10030542.html