You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用django-cors-headers时,如何为2条路由禁用CORS并保留其余规则?

解决django-cors-headers指定路由允许全来源CORS的问题

首先纠正你之前的两个问题:

  1. 你的CORS_URLS_REGEX正则有语法错误,缺少闭合的)和结束符$,正确的排除写法应该是r'^(?!/api/test1/|/api/test2/).*$'
  2. 即便正则写对了,这个逻辑也不符合你的需求——CORS_URLS_REGEX是指定哪些路由要应用CORS中间件,排除的路由不会被处理,也就不会返回Access-Control-Allow-Origin头,浏览器反而会拦截跨域请求,而不是允许所有来源。

下面是两种可行的实现方式:

方法一:用CORS_ALLOWED_ORIGINS_CALLABLE动态判断(推荐)

这个方法利用django-cors-headers的回调配置,根据请求路径动态返回允许的来源:

  1. 在settings.py中添加或修改以下配置:
# 你的原有白名单配置(旧版本django-cors-headers用CORS_ORIGIN_WHITELIST)
CORS_ORIGIN_WHITELIST = ['https://your-approved-domain1.com', 'https://your-approved-domain2.com']
# 如果你用的是django-cors-headers 3.0+,替换成下面这行
# CORS_ALLOWED_ORIGINS = ['https://your-approved-domain1.com', 'https://your-approved-domain2.com']

def cors_allowed_origins(request):
    # 匹配目标路由,允许所有来源
    if request.path.startswith('/api/test1/') or request.path.startswith('/api/test2/'):
        return '*'
    # 其他路由返回白名单域名
    return CORS_ORIGIN_WHITELIST

# 启用回调函数
CORS_ALLOWED_ORIGINS_CALLABLE = cors_allowed_origins
  1. 确保corsheaders.middleware.CorsMiddleware已经添加到MIDDLEWARE列表中,且顺序正确(放在django.middleware.common.CommonMiddleware之后)。

方法二:自定义中间件针对特定路由处理

如果需要更精细的控制,可以给目标路由单独应用自定义的CORS中间件:

  1. 创建自定义中间件文件(比如myapp/middleware.py):
from corsheaders.middleware import CorsMiddleware
from corsheaders.conf import settings

class AllowAllCorsMiddleware(CorsMiddleware):
    def process_response(self, request, response):
        # 强制设置允许所有来源
        response["Access-Control-Allow-Origin"] = "*"
        # 保留凭证配置(如果你的项目需要)
        if settings.CORS_ALLOW_CREDENTIALS:
            response["Access-Control-Allow-Credentials"] = "true"
        # 按需添加其他CORS头
        response["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE, OPTIONS"
        response["Access-Control-Allow-Headers"] = "*"
        return response
  1. 在urls.py中给目标路由应用这个中间件:
from django.urls import path
from .views import test1_view, test2_view, other_view
from .middleware import AllowAllCorsMiddleware

urlpatterns = [
    # 给指定路由应用自定义全来源CORS中间件
    path('api/test1/', AllowAllCorsMiddleware.as_view(view_func=test1_view), name='test1'),
    path('api/test2/', AllowAllCorsMiddleware.as_view(view_func=test2_view), name='test2'),
    # 其他路由使用默认的CORS中间件(依赖全局配置的白名单)
    path('api/other/', other_view, name='other'),
]

注意:这种方法需要确保全局的CorsMiddleware已经在MIDDLEWARE中,且自定义中间件的顺序不会冲突。


内容的提问来源于stack exchange,提问作者Trương Đức Vinh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 03:00:55