1

Estoy haciendo una tienda en línea y al momento en que no inicio sesión con mi usuario si ejecuta la acción correctamente de agregar productos en el carrito, pero en cambio cuando cuando inicio sesión con mi usuario no ejecuta la acción correctamente de agregar productos en el carrito.

Los errores que marca son:

cart.js:51 POST http://127.0.0.1:8000/update_item/ 404 (Not Found)
updateUserOrder @   cart.js:51
(anonymous) @   cart.js:13

Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
Promise.then (async)
updateUserOrder @ cart.js:62
(anonymous) @ cart.js:13

El código que tengo que estoy ejecutando es este, no estoy poniendolo completo porque no me deja integrarlo todo, así que puse un enlace para más detalle sobre el código que estoy ejecutando:

MÁS DETALLES sobre el código Descripción de código aquí

Este en el archivo general js:


    var updateBtns = document.getElementsByClassName('update-cart')
    
    for (i = 0; i < updateBtns.length; i++) {
        updateBtns[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') {
                addCookieItem(productId, action)
            }else{
                updateUserOrder(productId, action)
            }
        })
    }
    
    function addCookieItem(productId, action) {
        console.log('User is not authenticated')
    
        if (action == 'add') {
            if (cart[productId] == undefined) {
                cart[productId] = {'quantity':1}
    
            }else{
                cart[productId]['quantity'] += 1
            }
        }
    
    
        if (action == 'remove') {
            cart[productId]['quantity'] -= 1
    
            if (cart[productId]['quantity'] <= 0) {
                console.log('Item should be deleted')
                delete cart[productId];
            }
        }
        console.log('Cart:', cart)
        document.cookie = 'cart=' + JSON.stringify(cart) + ";domain=;path=/"
    
        location.reload()
    }
    
    
    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) => {
                location.reload()
            });
    }

archivo HTML base incluyedo esta función de js:

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

        function getToken(name) {
            var cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var 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 = getToken('csrftoken');

        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)
    

    </script>

MÁS DETALLES sobre el código Descripción de código aquí

2 respuestas 2

2

Tu problema no es en el código para realizar un post se necesita el token y en tu usuario no le has generado ningún token así que cuando quieres hacer un movimiento el programa busca el token de tu usuario y al no tenerlo te manda el error

Tienes 2 soluciones

1.- Generarle el token a tu usuario #recomendada

2.- Modificar lo para que no te pida token al usarlo

Recomendaría que le generaras token ya que en el momento de producción seria malo que no te pidiera token para hacer movimientos.

2
  • ¿Por qué no detecta el token se supone que están? el 10 nov. 2020 a las 2:58
  • Ya verificaste en tu base de datos que tenga token? el 10 nov. 2020 a las 4:54
1

Una solución sencilla que puedes probar, sería añadir los tokens necesarios en el JavaScript donde estás haciendo la petición y en tu HTML.

JavaScript

 function updateUserOrder(productId, action) {
        console.log('User is authenticated, sending data...')
    
        var url = '/update_item/'
    
        fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                csrfmiddlewaretoken: '{{ csrf_token }}', <-- Añade ésta linea
                'X-CSRFToken': csrftoken,
            },
            body: JSON.stringify({ 'productId': productId, 'action': action })
        })
            .then((response) => {
                return response.json();
            })
            .then((data) => {
                location.reload()
            });
    }

Main HTML

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

   /// funcion getToken()

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.