Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

169
Vistas
Can't make POST request via fetch javascript to django rest api

i just started to learn front-end and javascript. So, previously i made simple api via django rest framework. And now - start to test it via fetch-api of javascript. GET - no problem - it works well. POST - i got a message like: "415 Unsupported media type".

Here my simplified html-file (tryjs.html) with included fetch POST request:

<!DOCTYPE html>
<html>

<head>
</head>

<body>
     <script>
        let myurl2 = "http://127.0.0.1:8000/myfamily/";
        async function myfu() {
            let response = await fetch(myurl2, {
                mode: "no-cors",
                method: 'POST',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({firstname: "first", secondname: "second"})
            })
        };
        myfu();
    </script>
</body>

</html>

Looks like pretty simple and nothing special.

Here - the model.py from drf:

from django.db import models


class Family(models.Model):
    firstname = models.CharField(max_length=20)
    secondname = models.CharField(max_length=20)

    def __str__(self):
        return self.firstname

And serializers.py:

from rest_framework import serializers
from .models import Family


class FamilySerializer(serializers.ModelSerializer):
    class Meta:
        model = Family
        fields = ('firstname', 'secondname')

And view:

from rest_framework import viewsets
from .models import Family
from .serializers import FamilySerializer


class FamilyViewSet(viewsets.ModelViewSet):
    queryset = Family.objects.all()
    serializer_class = FamilySerializer

And urls.py of applications (added to urls.py of project):

from django.urls import path
from rest_framework.routers import SimpleRouter
from .views import FamilyViewSet
from django.views.generic import TemplateView


router = SimpleRouter()
router.register('', FamilyViewSet, basename="family")

urlpatterns = [
    path('tryjs/', TemplateView.as_view(template_name="tryjs.html")),
]

urlpatterns += router.urls

I do GET and POST request via postman - everything works fine. I do GET request via javascript script (i've delited this part from code above) - it works fine either. As soon, as i try to make POST request via js script above - i get a failure about wrong media type. Please, help. I tried a lot. And it's so simple case. However...it doesn't work(

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

you are getting wrong media type because you have set mode: "no-cors", which makes Content-Type header to be immutable. so setting it to "application/json" will automatically transformed to "text/plain". keep mode :"cors" and it will work.

No need to write the js code yourself, you will get the code from postman itself. try using that

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda