0

视图.py

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

    print('Action:', action)
    print('productId:', productId)
    
    return JsonResponse('Item was added', safe=False)

购物车.js

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

    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 getCookie,听说这个脚本可以解决这个问题。但是,它没有帮助。

function getToken(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 besgin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }   
    }
    return cookieValue;
}
const csrftoken = getToken('csrftoken');

仍然错误:POST http://127.0.0.1:8000/update_item/ 500(内部服务器错误)updateUserOrder 未捕获(承诺中) SyntaxError: Unexpected token < in JSON at position 0

4

0 回答 0