请求中不支持的媒体类型“text/plain;charset=UTF-8”。Django Rest Framework 的 NextJS API 错误

Ton*_*Ton 7 javascript python django-rest-framework next.js

我开始学习 Web 开发,并尝试使用 NextJS 和 Django Rest Framework 构建一个网站。NextJS 代理 API 端点,它可以很好地获取数据,但我很难让它在 POST 请求上工​​作。我读取请求本身计算内容类型,因此无需覆盖,但出现以下错误:

请求中不支持的媒体类型“text/plain;charset=UTF-8”。

如果我覆盖,则错误将更改为类型集:

请求中不支持的媒体类型“application/json;charset=utf-8”。

我尝试使用FormData,错误改为:

多部分表单解析错误 - 多部分中的边界无效:无

我在这个问题上读到的内容我不应该这样覆盖。

这是 Nexts.JS 页面:

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>
  );
}
Run Code Online (Sandbox Code Playgroud)

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);      
}
Run Code Online (Sandbox Code Playgroud)

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}'
Run Code Online (Sandbox Code Playgroud)

django 序列化器.py:

class CountrySerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = models.Country
        fields = "__all__"
Run Code Online (Sandbox Code Playgroud)

Django 视图.py:

class CountryViewSet(viewsets.ModelViewSet):
    queryset = models.Country.objects.all()
    serializer_class = serializers.CountrySerializer
Run Code Online (Sandbox Code Playgroud)

django urls.py:

router.register('countries', views.CountryViewSet)
Run Code Online (Sandbox Code Playgroud)

我可以使用 Django Rest Framework Web Browsable API 进行 POST,所以我想这在后端一切都很好,但我无法将 NextJS POST 到 API。我究竟做错了什么?

Jor*_*wal 11

我想到了两件事:

  • 确保您的请求是正确的headers
  • 确保数据格式正确。您可能需要对数据使用 JSON.stringify (也许您之前已经完成了,我无法从您当前的代码中看出)
response = await fetch(apiEnd, {
      method: "POST",
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(javascriptObject)
    });
Run Code Online (Sandbox Code Playgroud)