[英]Why am I getting a 400 bad request error? Using the Django Rest framework as a backend and React as a frontend for my web application
我正在開發一個使用 openweathermap api 的簡單 web 應用程序。 有一個 api 調用返回 api 數據的視圖,並顯示用戶鍵入的特定城市的天氣的溫度和描述。
下面的 api 調用是對允許用戶保存他們選擇的特定天氣數據的新功能的另一個調用。 它從 state 獲取 temp & desc,並將其發送到后端視圖。 然后視圖將該數據保存到數據庫中,並返回一個響應,然后我將使用該響應在同一個 api 調用中顯示數據。 它給了我一個 400 錯誤。 我在控制台記錄了 temp 和 desc,它們都打印正確,所以我不會將未定義的數據發送到后端。 這可能是我序列化數據的方式嗎?
前端 api 調用
const saveWeather = (temperature, description) => {
const requestOptions = {
method: "POST",
headers: { "Content-Type": "application/json"},
body: JSON.stringify({
temperature: temperature,
description: description
})
};
fetch("/api/savedweather", requestOptions)
.then((response) => {
if (response.ok) {
console.log("OK");
}
})
.catch((error) => {
console.log(error);
});
}
看法
class SaveWeather(APIView):
serializer_class = WeatherSerializer
def post(self, request, format=None):
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
temperature = serializer.data.get('temperature')
description = serializer.data.get('description')
weather = Weather(temperature=temperature, description=description)
weather.save()
return Response(WeatherSerializer(weather).data, status=status.HTTP_201_CREATED)
return Response({'Bad Request': "Invalid Data..."}, status=status.HTTP_400_BAD_REQUEST)
Model
from django.db import models
class Weather(models.Model):
temperature = models.IntegerField(null=False, default=1)
description = models.CharField(max_length=50)
串行器 Class
from .models import Weather
from rest_framework import serializers
class WeatherSerializer(serializers.ModelSerializer):
class Meta:
model = Weather
fields = ('temperature', 'description')
如果不知道 model 和序列化程序定義,就很難分辨。
但由於它顯然似乎是 serializaer 驗證錯誤,您可以使用serializer.errors
字段檢查 serializaer 拋出的錯誤。
if serializer.is_valid():
...
return Response(WeatherSerializer(weather).data, status=status.HTTP_201_CREATED)
print(serializer.errors)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.