Unsupported media type "text/plain;charset=UTF-8" in request. NextJS API error with Django Rest Framework

Viewed 3479

I'm starting to learn web development and I'm trying to build an website using NextJS and Django Rest Framework. NextJS proxies APIs endpoints and it worked well to get data, but I'm struggling to make it work on a POST request. I read the request itself figures the content-type, so there's no need to overwrite, but i get the following error:

Unsupported media type "text/plain;charset=UTF-8" in request.

If I overwrite then the error changes to the type set:

Unsupported media type "application/json; charset=utf-8" in request.

I tried to use FormData and the error changed to:

Multipart form parse error - Invalid boundary in multipart: None

Which I read on this question I shouldn't overwrite like this.

Here's the Nexts.JS page:

export default function NewEvent({ ...props }) {

  const saveEvent = async event => {
    event.preventDefault()
    const formData = new FormData(event.target);
    const res = await fetch("api/countries/",{
      method:"POST",
      body: formData
    })
    console.log(res)
  } 

  return (
      <Stack padding={4} as="form" onSubmit={saveEvent} >
          <Input name="name" placeholder="Insert the event name here" />
          <Input name="code" placeholder="Insert the event name here" />
        <Button type="submit"> Save </Button>
      </Stack>
  );
}

the NextJS /api/countries.js:

export default async function handler(req, res) {
  
  let response;

  if (req.method === "POST") {    
    const apiEnd = `http://127.0.0.1:8000/countries/`;
    response = await fetch(apiEnd, {
      method: "POST",
      body:req.body
    });
  }

  const json = await response.json();
  res.json(json);      
}

the django models.py:

class Country(models.Model):
    name = models.CharField(max_length=20, blank=False, null=False)
    code = models.CharField(max_length=5, blank=True, null=True)

    def __str__(self):
        """String for representing the Model object."""
        return f'{self.name}'

django serializers.py:

class CountrySerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = models.Country
        fields = "__all__"

django views.py:

class CountryViewSet(viewsets.ModelViewSet):
    queryset = models.Country.objects.all()
    serializer_class = serializers.CountrySerializer

django urls.py:

router.register('countries', views.CountryViewSet)

I can POST using the Django Rest Framework Web Browsable API so I guess it's all good on the backend, but I cant make NextJS POST to the API. What am I doing wrong?

1 Answers

There are two things that come to mind:

  • Making sure your request has the right headers
  • Making sure the data is properly formatted. You might need to use JSON.stringify on your data (maybe you've done it ealier, I cannot tell from your current code)
response = await fetch(apiEnd, {
      method: "POST",
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(javascriptObject)
    });
Related