Homologous cross-domain issues

1. Cross-Domain

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

2. solve cross-domain: CORS

CORS,跨站资源共享,本质:设置响应头。

from django.shortcuts import render,HttpResponse

def json(request):
    response = HttpResponse("JSONasdfasdf")
    response['Access-Control-Allow-Origin'] = "*"
    return response
    

3. When the cross-domain, a request is sent twice?

When cross-domain request will be divided into two types:

  • A simple request, send a request.

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

  • Preflight

  • request

    @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. Summary

  1. Due to browser limitations have "same origin policy", so cross-domain Ajax requests on the browser, the browser will be blocked.
  2. To solve cross-domain
    • No cross-domain
    • CORS (cross-site sharing of resources, nature is set up in response to solve).
      • A simple request: a request sending
      • Complex requests: a request sent twice, the first request to do preflight options, and then send real request

Guess you like

Origin www.cnblogs.com/fengqiang626/p/11876556.html