Ответ Django теряется, а обещание fetch не приходит.

У меня есть форма, которая получает js для выполнения серии валидаций и затем отправляет информацию на сервер с помощью fetch (простой api). Правда в том, что я не очень понимаю, почему возникает ошибка, следует отметить, что в разработке она работала отлично, но теперь, когда она находится в продакшене, размещенном на heroku, возникает эта проблема, код фетча выглядит следующим образом.

formulario.addEventListener('submit', (e) => {
    e.preventDefault();

    fetch('https://portafolioadrian.herokuapp.com/contacto', {
      method: 'POST',
      body: JSON.stringify({
        nombre: document.querySelector('#nombre').value,
        correo: document.querySelector('#correo').value,
        telefono: document.querySelector('#telefono').value,
        mensaje: document.querySelector('#form__message').value,
        terminos : document.getElementById('terminos').checked,
      }),
      headers: {
        'X-CSRFToken': getCookie('csrftoken'), "Accept": "application/json", 'Content-Type': 'application/json'} 
    })
    .then(res => res.json())
    .then(res => {
      if (res.success) {
        formulario.reset();
    
            document.getElementById('form__message-success').classList.add('form__message-success-active');
            setTimeout(() => {
                document.getElementById('form__message-success').classList.remove('form__message-success-active');
            }, 5000);
    
            document.querySelectorAll('.form__group-correct').forEach((icono) => {
                icono.classList.remove('form__group-correct');
            });
      }else{
        document.getElementById('form__message').classList.add('form__message-active');
      }
    })  
});

Когда я отправляю его, я получаю следующую ошибку

через консоль.

Uncaught (in promise) SyntaxError: Неожиданная лексема < в JSON в позиция 0

<<<0><0>>В разделе сети статус на POST - 301 Moved Permanently, я провел некоторые исследования и попробовал перенаправления, но не нашел решения <<<1><1>>> <<<<0><0>>Приложение urls.py выглядит так:<<<<1><1>>>
urlpatterns = [
    path('', views.contacto, name='contacto'),
    path('mensajes/', views.mensajes, name='mensajes'),
]
<<<<0><0>>>Вид следующий:

def contacto(request):

    if request.method == "POST":
        
        #Obtengo los datos y los convierto en diccionario y asigno datos a variables
        data = json.loads(request.body)
        nombre = data['nombre']
        correo = data['correo']
        telefono = data['telefono']
        mensaje = data['mensaje']
        terminos = data['terminos']

        #Creo y guardo el registro en la base de datos 
        instancia = Contacto.objects.create(nombre = nombre, email = correo, telefono = telefono, mensaje = mensaje, terminos = terminos)
        instancia.save()

        #Devuelvo la respuesta al fetch para terminar de renderizar datos en la plantilla de contacto
        return JsonResponse('success')

    else:
        #renderizo el formulario html
        return render(request, 'contacto/contacto.html')
Вернуться на верх