我开始学习 Web 开发,并且正在尝试使用 NextJS 和 Django Rest Framework 构建一个网站。 NextJS 代理 API 端点,它可以很好地获取数据,但我正在努力使其在 POST 请求上工作。我阅读了请求本身的内容类型,因此无需覆盖,但出现以下错误:
Unsupported media type "text/plain;charset=UTF-8" in request.
如果我覆盖,则错误更改为类型集:
Unsupported media type "application/json; charset=utf-8" in request.
我尝试使用 FormData 并且错误更改为:
Multipart form parse error - Invalid boundary in multipart: None
我在 this question 上读到的我不应该这样覆盖。
这是 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>
);
}
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);
}
Django 模型.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 序列化器.py:class CountrySerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = models.Country
fields = "__all__"
Django View .py:class CountryViewSet(viewsets.ModelViewSet):
queryset = models.Country.objects.all()
serializer_class = serializers.CountrySerializer
Django urls.py:router.register('countries', views.CountryViewSet)
我可以使用 Django Rest Framework Web Browsable API 进行 POST,所以我想它在后端都很好,但是我不能让 NextJS POST 到 API。我究竟做错了什么?
最佳答案
有两件事浮现在脑海:
headers
response = await fetch(apiEnd, {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(javascriptObject)
});
关于javascript - 请求中不支持的媒体类型 "text/plain;charset=UTF-8"。 NextJS API 错误与 Django Rest Framework,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67543522/