zoukankan      html  css  js  c++  java
  • 跨域(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
  • 相关阅读:
    【python 待做】
    【python 第13日】网络通信socket socketserver
    【python第11日】自动生成项目目录 安全插入本文件夹下文件,即使别人引用也可以
    【python 第12日】 except异常
    【python 第10日】打飞机的小游戏 pygame
    【python 第9日】上下文 类装饰器 元类 属性描述符扩展
    Python(2.7)-字符串
    Python(2.7)-字典(dict)
    Python(2.7)-列表(list)
    mysql linux centos yum 安装
  • 原文地址:https://www.cnblogs.com/ls13691357174/p/9898696.html
Copyright © 2011-2022 走看看