欢迎来到赛兔子家园

drf解决跨域问题

跨域问题

当前浏览器访问地址:http://127.0.0.1:8011/

发送网络请求:https://home.cnblogs.com/u/qingchengzi/api/xxx/xxx时 ,浏览器会对跨域请求响应进行拦截处理。

解决方案:本质上处理跨域,添加一些响应头,告诉浏览器放行;

views.py

from rest_framework.response import Response
from rest_framework.views import APIView


class HomeView(APIView):

    def get(self, request, *args, **kwargs):
        response = Response("OK")
        print("原始响应头:", response.headers)
        # 任意网址
        response["Access-Control-Allow-Origin"] = "*"
        # 任意的请求方式
        response["Access-Control-Allow-Methods"] = "*"  # "PUT,DELETE,GET,POST"
        # 允许任意的请求头
        response["Access-Control-Allow-Headers"] = "*"
        print("添加允许跨域后的响应头:", response.headers)
        return response

程序输出:

原始响应头: {'Content-Type': 'text/html; charset=utf-8'}
添加允许跨域后的响应头: {'Content-Type': 'text/html; charset=utf-8', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': '*', 'Access-Control-Allow-Headers': '*'}

跨域请求

跨域请求发送时请求:

1、简单请求:1个请求

2、复杂请求:2个请求

   2.1 OPTIONS请求(预检)。

      2.2 真正请求。

区分规则:

条件1:请求方式:HEAD、GET、POST
条件2:请求头信息:
      content-Type:对应的值是以下三个中的任意一个
         application/x-www-form-urlencoded
         multipart/form-data
         text/plain

注意:同时满足以上两个条件时,是简单请求,否则为复杂请求。

应用drf框架

写到中间件process_response

drf根目录/utils/ext/middlewares/auth.py

from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse


class AuthMiddleware(MiddlewareMixin):

    def process_request(self,request):
        if request.method == "OPTIONS":
            return HttpResponse("")


    def process_response(self, request, response):
        # 任意网址
        response["Access-Control-Allow-Origin"] = "*"
        # 允许任意的请求头
        response["Access-Control-Allow-Headers"] = "*" # "PUT,DELETE,GET,POST"
        # 任意的请求方式
        response["Access-Control-Allow-Methods"] = "*"
        return response

settings.py

MIDDLEWARE = [
    'utils.ext.middlewares.auth.AuthMiddleware'  #跨域中间件路径
]

 

posted on 2024-05-16 20:36  赛兔子  阅读(4)  评论(0编辑  收藏  举报

导航