同源跨域問題

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請求作預檢,而後再發送真正請求
相關文章
相關標籤/搜索