• Django框架12 /同源、跨域、CORS


    Django框架12 /同源、跨域、CORS

    1. 同源策略

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

    2. 同源是指:域名,协议,端口相同。

    3. 如果非同源,那么在请求数据后,浏览器得到非同源的响应数据时会在控制台中报一个异常,提示拒绝访问。

    2. 跨域

    • 当一个请求url的协议、域名、端口三者之间任意一个与当前页面url不同即为跨域。

    • 由于浏览器具有“同源策略”的限制。

    • 如果在同一个域下发送ajax请求,浏览器的同源策略不会阻止。

    • 如果在不同域下发送ajax请求,浏览器的同源策略会阻止。

    3. 解决跨域:CORS/跨域资源共享

    • 本质在数据返回值设置响应头

      from django.shortcuts import render,HttpResponse
      
      def json(request):
          response = HttpResponse("JSONasdfasdf")
          response['Access-Control-Allow-Origin'] = "*"
          return response
      
    • 在跨域时,发送的请求会分为两种

      1.简单请求,发一次请求

      # 设置响应头就可以解决
      from django.shortcuts import render,HttpResponse
      
      def json(request):
          response = HttpResponse("JSONasdfasdf")
          response['Access-Control-Allow-Origin'] = "*"
          return response
      

      2.复杂请求,发两次请求,先进行预检/再发送请求

      预检: 其实做检查,检查如果通过则允许传输数据,检查不通过则不再发送真正想要发送的消息

      @csrf_exempt
      def put_json(request):
          response = HttpResponse("JSON复杂请求")
          if request.method == 'OPTIONS':
              # 处理预检
              response['Access-Control-Allow-Origin'] = "*"
              response['Access-Control-Allow-Methods'] = "PUT"
          	response['Access-Control-Allow-Headers'] = 'content-type,application/json'
              return response
          elif request.method == "PUT":
              return response
      
      # 条件:
      1、请求方式:HEAD、GET、POST
      2、请求头信息:
          Accept
          Accept-Language
          Content-Language
          Last-Event-ID
          Content-Type 
          # Content-Type对应的值是以下三个中的任意一个
          application/x-www-form-urlencoded
          multipart/form-data
          text/plain
      
      # 注意:同时满足以上两个条件时,则是简单请求,否则为复杂请求
      
  • 相关阅读:
    ADO.NET 中的数据并发
    net中前台javascript与后台c#函数相互调用
    js正则函数match、exec、test、search、replace、split使用介绍集合
    jQuery遍历Table tr td td中包含标签
    SQL你必须知道的-查询聚合分组排序
    haut-1280 诡异的迷宫
    int、long long等的取值范围
    codeforce 855B
    nyoj-2357
    codeforces 858A
  • 原文地址:https://www.cnblogs.com/liubing8/p/11695737.html
Copyright © 2020-2023  润新知