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

Django发送Cookie但React前端无法接收的问题求助

问题解决建议

核心原因分析

你遇到的问题主要来自浏览器跨域安全限制、HttpOnly Cookie的特性,以及Django与前端请求的配置不匹配这三个方面。

具体解决步骤

1. 修正前端fetch请求的凭证配置

fetch API默认不会在跨域请求中携带或暴露Cookie,必须显式设置credentials参数:跨域场景用'include',同域场景用'same-origin'。

修改前端代码:

export async function fetchProductsBySlugs(slugs, setterFunc, startDate, endDate, dateChange) {
  const [start, end] = parseDates(startDate, endDate)

  try {
    const response = await fetch(`${SERVER_ADDRESS}/api/products/products/list/?slugs=${slugs.join(',')}&${datesUrlString(start,end,dateChange)}`, {
      credentials: 'include' // 新增凭证配置
    });

    // 注意:若Cookie带HttpOnly属性,此处无法通过get('Set-Cookie')读取,但浏览器会自动存储
    const cookies = response.headers.get('Set-Cookie')
    console.log(cookies)

    const products = await response.json();

    setterFunc(products);
    return products;
  } catch (error) {
    throw error;
  }
}

2. 配置Django跨域允许凭证(跨域场景必做)

如果前后端是跨域部署,需通过django-cors-headers配置允许凭证传递:

  • 确保已安装django-cors-headers,并在INSTALLED_APPS和MIDDLEWARE中添加该组件
  • 在settings.py中添加以下配置:
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOWED_ORIGINS = [
    "http://your-frontend-domain:port",  # 替换为你的前端实际地址
]
# 开发环境临时允许所有域名(生产环境禁止使用)
# CORS_ALLOW_ALL_ORIGINS = True

3. 改用Django内置set_cookie方法设置Cookie

直接赋值response['Set-Cookie']可能覆盖其他Cookie头,改用response.set_cookie()更可靠,能自动处理多Cookie场景:

修改中间件代码:

class DeviceCookieMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        new_customer = None

        if 'device' not in request.COOKIES:
            new_customer = Customer.objects.create()

            # 替换直接赋值为set_cookie方法
            response.set_cookie(
                key='device',
                value=new_customer.device,
                max_age=3600,
                secure=True,
                httponly=True,
                samesite='None'
            )

        request.new_customer = new_customer
        print(response.headers)
        return response

4. 理解HttpOnly Cookie的特性

你设置了HttpOnly属性,这意味着前端JavaScript无法读取该Cookie(包括response.headers.get('Set-Cookie')和document.cookie),这是正常的安全设计,用于防范XSS攻击。但浏览器会自动存储该Cookie,后续符合规则的请求会自动携带它。

若确实需要前端读取该Cookie,可去掉httponly=True,但此操作会增加XSS风险,不建议生产环境使用。

5. 验证Cookie存储状态

虽然前端JS无法读取HttpOnly Cookie,但可通过浏览器开发者工具验证:

  • 打开控制台 → 「应用(Application)」标签 → 「存储(Storage)」→ 「Cookie」→ 查看对应域名下是否存在device Cookie

内容的提问来源于stack exchange,提问作者Jacob Simerly

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 08:52:45