zoukankan      html  css  js  c++  java
  • 同源跨域问题

    1.跨域

    由于浏览器具有“同源策略”的限制。
    如果在同一个域下发送ajax请求,浏览器的同源策略不会阻止。
    如果在不同域下发送ajax,浏览器的同源策略会阻止。
    

    2.解决跨域:CORS

    CORS,跨站资源共享,本质:设置响应头。
    
    from django.shortcuts import render,HttpResponse
    
    def json(request):
        response = HttpResponse("JSONasdfasdf")
        response['Access-Control-Allow-Origin'] = "*"
        return response
        
    

    3.跨域时,发送了2次请求?

    在跨域时,发送的请求会分为两种:

    • 简单请求,发一次请求。

      设置响应头就可以解决
      from django.shortcuts import render,HttpResponse
      
      def json(request):
          response = HttpResponse("JSONasdfasdf")
          response['Access-Control-Allow-Origin'] = "*"
          return response
      
      
    • 复杂请求,发两次请求。

    • 预检

    • 请求

      @csrf_exempt
      def put_json(request):
          response = HttpResponse("JSON复杂请求")
          if request.method == 'OPTIONS':
              # 处理预检
              response['Access-Control-Allow-Origin'] = "*"
              response['Access-Control-Allow-Methods'] = "PUT"
              return response
          elif request.method == "PUT":
              return response
      
    条件:
        1、请求方式:HEAD、GET、POST
        2、请求头信息:
            Accept
            Accept-Language
            Content-Language
            Last-Event-ID
            Content-Type 对应的值是以下三个中的任意一个
                                    application/x-www-form-urlencoded
                                    multipart/form-data
                                    text/plain
     
    注意:同时满足以上两个条件时,则是简单请求,否则为复杂请求
    

    4.总结

    1. 由于浏览器具有“同源策略”的限制,所以在浏览器上跨域发送Ajax请求时,会被浏览器阻止。
    2. 解决跨域
      • 不跨域
      • CORS(跨站资源共享,本质是设置响应头来解决)。
        • 简单请求:发送一次请求
        • 复杂请求:发送两次请求,先options请求做预检,然后再发送真正请求
  • 相关阅读:
    line-height:150%和line-height:1.5的区别
    javascript: with 表单验证
    CSS实现背景透明,文字不透明,兼容所有浏览器
    关于伪类元素:before和:after
    图片预览实例分享
    微信浏览器取消缓存的方法
    学习笔记(四):jQuery之动画效果
    学习笔记(三):jQuery之DOM
    Git 常用命令
    开发规范(三)数据库 By 阿里
  • 原文地址:https://www.cnblogs.com/fengqiang626/p/11876556.html
Copyright © 2011-2022 走看看