簡體   English   中英

Django X-CSRF 令牌不能在 javascript 提取中設置

[英]Django X-CSRF token cannot be set in javascript fetch

我正在嘗試在 javascript 中生成一個 csrf 令牌,並將其與使用 fetch 的 POST 請求一起使用。 在我的 html 中,我在head下有以下腳本標記來生成 csrf 令牌:

<head>
    <script type="text/javascript">
        var user = '{{request.user}}'

        function getCookie(name) {
            let cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                const cookies = document.cookie.split(';');
                for (let i = 0; i < cookies.length; i++) {
                    const cookie = cookies[i].trim();
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) === (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
        var csrftoken = getCookie('csrftoken');

        console.log(csrftoken)
    </script>
</head>

然后在body下,我有以下腳本標簽,我在其中檢索 csrftoken 變量並將其傳遞給fetch()中的'X-CSRFToken' header :

<body>
    <script type="text/javascript">
        console.log('Hello World')
        console.log(csrftoken)

        var updateButtons = document.getElementsByClassName('update-cart')

        for(i = 0; i < updateButtons.length; i++){
            updateButtons[i].addEventListener('click', function(){
                var productId = this.dataset.product
                var action = this.dataset.action
                console.log('productId: ', productId, 'action: ', action)

                console.log('user: ', user)

                if(user === 'AnonymousUser'){
                    console.log('Not logged in.')
                }else{
                    updateUserOrder(productId, action)
                }
            })
        }

        function updateUserOrder(productId, action){
            console.log('User is authenticated. Sending data...')
            console.log(csrftoken)

            var url = '/update_item/'

            fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type':'application/json',
                    'X-CSRFToken':csrftoken,
                },
                body: JSON.stringify({'productId': productId, 'action': action})
            })

            .then((response) => {
                return response.json()
            })

            .then((data) => {
                console.log('data: ', data)
            })
        }
    </script>
</body>

所有console.log()調用都會顯示csrftoken變量,但我仍然遇到以下異常:

(index):169 POST http://127.0.0.1:8000/update_item/ 500 (Internal Server Error)
updateUserOrder
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

視圖.py,

def update_item(request):
    data = json.loads(request.data)
    product_id = data['productId']
    action = data['action']

    print('action: ', action)
    print('product_id: ', product_id)

    customer = request.user.customer
    product = Product.objects.get(id=product_id)

    order, created = Order.objects.get_or_create(customer=customer, complete=False)
    orderitem, created = OrderItem.objects.get_or_create(order=order, product=product)

    if action == 'add':
        orderitem.quantity += 1
    elif action == 'remove':
        orderitem.quantity -= 1

    orderitem.save()

    if orderitem.quantity <= 0:
        orderitem.delete()

    return JsonResponse('Item was added.', safe=False)

我似乎無法弄清楚這是語法錯誤還是我將“X-CSRFToken” header 設置錯誤。 其他類似的答案沒有幫助。

解決了。 我的 javascript 或其中的 csrftoken 變量不是問題。 而是在我的服務器代碼中。 在 views.py 中,我輸入data = json.loads(request.data) 但它應該是data = json.loads(request.body)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM