You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React向Django REST Framework发POST请求遇400 Bad Request问题

React向Django发送POST请求出现400 Bad Request的解决方法

一、修正前端请求格式(最直接的问题)

你的请求存在请求头与请求体格式不匹配的问题,这是导致400错误的核心原因:

  1. 你设置了Content-Type: application/x-www-form-urlencoded,但请求体用JSON.stringify(blog)生成了JSON字符串,Django无法解析这种不匹配的格式
  2. 前端不需要添加Access-Control-*系列请求头,这些是服务器返回给浏览器的响应头,前端发送请求时添加无效
  3. mode: 'no-cors'会屏蔽浏览器的响应信息,不利于排查问题,既然已经解决CORS,就改用正常的跨域模式

修改后的options代码:

const options={
  mode: 'cors', 
  cache: 'no-cache',
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    "Content-Type": "application/json"
  },
  body : JSON.stringify(blog)
}

同时修正catch里的错误打印:把console.log(e);改成console.log(error);,才能看到真实的错误信息。

二、检查Django后端配置

1. 确认序列化器字段匹配

假设你的ProfileList是DRF的ListCreateAPIView,对应的序列化器必须完整包含模型的必填字段,示例如下:

from rest_framework import serializers
from .models import Radiologist

class RadiologistSerializer(serializers.ModelSerializer):
    class Meta:
        model = Radiologist
        fields = ['name', 'email', 'mobile_number', 'national_id', 'password']

2. 确认视图绑定序列化器

确保ProfileList视图正确指定序列化器:

from rest_framework import generics
from .models import Radiologist
from .serializers import RadiologistSerializer

class ProfileList(generics.ListCreateAPIView):
    queryset = Radiologist.objects.all()
    serializer_class = RadiologistSerializer

三、验证数据合法性

400错误也可能是数据不符合模型约束:

  • mobile_number和national_id的max_length=10,前端输入内容长度不能超过10,且不能重复
  • email必须是合法格式,且数据库中不存在重复值
  • password长度不能超过100

你可以查看Django控制台的输出,里面会详细说明哪个字段验证失败,快速定位问题。

四、直接测试后端接口(排查前后端问题)

用curl或Postman直接发送POST请求,验证后端接口是否正常:

curl -X POST http://localhost:8000/profiles/ \
  -H "Content-Type: application/json" \
  -d '{"name":"测试用户","email":"test@example.com","mobile_number":"1234567890","national_id":"0987654321","password":"test123456"}'

如果这个请求成功,说明问题在前端;如果也返回400,根据Django控制台的错误信息修正后端配置。

内容的提问来源于stack exchange,提问作者nashat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 02:20:30