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

Django后端无法获取前端JS设置的Cart Cookie问题求助

Django前端设置的Cart Cookie后端无法获取的问题

问题说明

我是Django新手,项目中遇到如下问题:通过JavaScript设置了JSON格式的cart Cookie,前端已确认Cookie创建成功,购物车内容能在控制台正常显示,但后端无法通过request.COOKIES获取该Cookie,终端打印request.COOKIES时看不到cart字段,代码进入KeyError分支,输出空购物车内容。

前端代码

function getCookie(name) {
    // Split cookie string and get all individual name=value pairs in an array
    var cookieArr = document.cookie.split(";");

    // Loop through the array elements
    for(var i = 0; i < cookieArr.length; i++) {
        var cookiePair = cookieArr[i].split("=");

        /* Removing whitespace at the beginning of the cookie name and compare it with the given string */
        if(name == cookiePair[0].trim()) {
            // Decode the cookie value and return
            return decodeURIComponent(cookiePair[1]);
        }
    }

    // Return null if not found
    return null;
}

var cart = JSON.parse(getCookie('cart'))

if (cart == undefined){
    cart = {}
    console.log('Cart Created!', cart)
    document.cookie ='cart=' + JSON.stringify(cart) + ";domain=;path=/";
}
console.log('Cart:', cart)

前端验证:浏览器开发者工具中可看到cart Cookie已创建,控制台能打印出购物车对象。

后端代码

def cart(request):
    print(request.COOKIES)
    if request.user.is_authenticated:
        customer = request.user.customer
        order, created = Order.objects.get_or_create(
            customer=customer,
            complete=False,
            )
        items = order.orderitem_set.all()
        cart_items = order.get_cart_items
    else:
        try:
            bag = json.loads(request.COOKIES['cart'])
            print('CART ITEMS:', bag)
        except KeyError:
            bag = {}
            print('CART ITEMS:', bag)

        items = []
        order = {
            'get_cart_total': 0,
            'get_cart_items': 0,
            }
        cart_items = order['get_cart_items']

        for i in bag:
            cart_items += bag[i]['quantity']

    context = {
        'items': items,
        'order': order,
        'cart_items': cart_items,
        }

    return render(request, 'cart/cart.html', context)

后端验证:终端打印request.COOKIES无cart字段,进入异常分支输出CART ITEMS: {}。

问题解决办法

1. 修正Cookie的domain设置

前端设置Cookie时,domain=;的写法会导致部分浏览器无法正确识别Cookie所属域名,进而无法在请求时携带给后端。建议移除domain参数,或者设置为当前域名(本地开发可设为localhost):

// 修改后设置Cookie的代码
document.cookie = 'cart=' + encodeURIComponent(JSON.stringify(cart)) + ";path=/";

2. 对JSON内容进行URI编码

JSON字符串可能包含逗号、空格等特殊字符,直接写入Cookie会导致解析异常,需要用encodeURIComponent对JSON内容编码,后端通过request.COOKIES获取后,json.loads会自动处理解码(Django会自动解码Cookie值)。

3. 验证Cookie的作用域

确保path=/正确设置,这样Cookie在整个网站范围内有效,避免请求后端接口时Cookie未被携带。

修改后重新测试,前端设置Cookie后,后端request.COOKIES就能获取到cart字段,正常解析购物车内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 00:55:25