反应公理发布错误:"Request failed with status code 400"



我正在创建一个前端应用程序,在django中使用后端并使用djangorestframework。在这里,我正在通过调用 API 端点来处理普通表单提交。我正在使用axios发出发布请求。我已经将 axios 方法放在 handleSubmit(( 方法中:

handleSubmit(event){
event.preventDefault();
const data = {
first_name: this.state.first_name,
last_name: this.state.last_name,
dob: this.state.dob,
sex: this.state.sex
};
axios.post('http://127.0.0.1:8000/profile/create/', data)
.then(res => console.log(res))
.catch(err => console.log(err));
};

在后端,我正在使用generics.CreateAPIView视图:

class CreateProfile(generics.CreateAPIView):
serializer_class = ProfileSerializer

网址:path('profile/create/', CreateProfile.as_view()),

models.py:

class Profile(models.Model):
MALE = 'M'
FEMALE = 'F'
TRANS = 'T'
NO_MENTION = 'NO'
GENDER_CHOICES = [
(MALE, 'Male'),
(FEMALE, 'Female'),
(TRANS, 'Trans'),
(NO_MENTION, 'Rather not say')
]
first_name = models.CharField(max_length=15)
last_name = models.CharField(max_length=15)
dob = models.DateField(auto_now=False)
sex = models.CharField(max_length=15, choices=GENDER_CHOICES)

当我提交表单时,控制台中显示此错误:Error: "Request failed with status code 400".

我做错了什么?

这是通过更改表单日期输入字段中的日期格式来解决的。根据Django REST框架,日期格式为YYYY-MM-DD。因此,我必须以相同的格式插入日期作为type="text",它解决了错误。

状态代码 400 表示错误请求。也就是说,客户端出错了。因此,观察客户端中的输入格式是否与 api 端点中所需的格式匹配非常重要。

400提示可能无效的表单数据。确保在表单数据中包含所有模型字段,根据模型定义,这些字段不可为空。其他限制也可能受到影响。如果您共享您的模型,这将使事情变得容易得多。

但是,这更像是,由于 CORS 保护,您的请求被阻止。

通过以下方式安装 django-cors

pip install django-cors-headers

然后在你的 settings.py

添加或更确切地说是附加

INSTALLED_APPS = [
...
'corsheaders',
...
]

以及

MIDDLEWARE = [  # Or MIDDLEWARE_CLASSES on Django < 1.10
...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
]

并定义您的 CORS 白名单,如下所示

CORS_ORIGIN_WHITELIST = [
"https://example.com",
"https://sub.example.com",
"http://localhost:8080",
"http://127.0.0.1:9000"
]

在这里查看 django-cors-headers 上的文档。

相关内容