同源跨域问题

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次请求?

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

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

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

  • 预检浏览器

  • 请求app

    @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
条件:
    一、请求方式:HEAD、GET、POST
    二、请求头信息:
        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请求作预检,而后再发送真正请求
相关文章
相关标签/搜索