解决跨域问题

Posted on 2022-11-27 21:19  呱呱呱呱叽里呱啦  阅读(27)  评论(0编辑  收藏  举报

解决跨域问题

自定义中间件,重写process_response,给响应头添加字段和字段值,处理简单请求和非简单请求

from django.utils.deprecation import MiddlewareMixin
from django.conf import settings
class Cors_MiddleWare(MiddlewareMixin):
    def process_response(self,request,response):
        response['Access-Control-Allow-Origin'] = settings.CORS_ALLOW_ORIGIN
        if request.method == 'OPTIONS':
            response['Access-Control-Allow-Headers'] = settings.CORS_ALLOW_HEADERS

        return response



CORS_ALLOW_ORIGIN = '127.0.0.1:8080'

CORS_ALLOW_HEADERS = (
    "accept",
    "accept-encoding",
    "authorization",
    "content-type",
    "dnt",
    "origin",
    "user-agent",
    "x-csrftoken",
    "x-requested-with",
    'token',
)


MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'luffyapi.utils.cors_middleware.Cors_MiddleWare', 
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

或者使用第三方模块:pip install django-cors-headers

# 注册app
INSTALLED_APPS = [
    ...
    'corsheaders',
]

# 添加中间件
MIDDLEWARE = [
    ...
    'corsheaders.middleware.CorsMiddleware',
]

# 允许跨域源
CORS_ORIGIN_ALLOW_ALL = True

# 允许的请求头
CORS_ALLOW_HEADERS = (
    "accept",
    "accept-encoding",
    "authorization",
    "content-type",
    "dnt",
    "origin",
    "user-agent",
    "x-csrftoken",
    "x-requested-with",

    # 额外允许的请求头
    'token',
)