Search code examples
javascriptjsondjangopostfetch

Javascript Fetch : Error Unexpected token < in JSON at position 0


I am sending a POST request to my Django view. When I run the code in local it works but when I run it on my apache server it gives me a 500 error. Could you help me, please !!

This is my code:

  form.addEventListener('submit', e=>{
            e.preventDefault()
            const baseInput = document.querySelector('#inputbaseform0')
            if(baseInput.value !== null){
                $('#loadMe').modal('show');
                let data = {}
                data['base'] = baseInput.value
                data['tiempo'] =tiempo.value
                data['otros'] =otros.value
       
                
                let url = "{% url 'cal' %}";
                
                fetch(url, {
                    method: "POST",
                    credentials: "same-origin",
                    headers: {
                        "X-CSRFToken": document.querySelector('#form0 input').value,
                        "Accept": "application/json",
                        "Content-Type": "application/json"
                    },
                    body: JSON.stringify(data)
                }).then(function(response){
                    return response.json();
                }).then(function(data){
                    console.log('ERROR: ', data.error)
                    baseData = parseFloat(data.base).toFixed(2)

                    deducir.value = data.porciento//porciento
                    
                    $('#loadMe').modal('hide');

                }).catch(function (e){
                    console.log('Error', e);
                    $('#loadMe').modal('hide');

                })
            }
        })
    })

Solution

  • Your problem is not in your js code. This code does exactly what you want, trying to parse response data as json. But your django view returns the 500 error page for some reason, and this page is html starting with "<".

    Logs can tell you why your django view throws an exception.