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

ReactJS POST请求无法向Django后端传递参数问题排查

解决React Axios + Django注册时参数丢失的Bad Request问题

问题根源

你的代码存在两个核心问题:

  • Axios用法错误:直接照搬Fetch的请求格式,把配置项和请求数据混在一起,导致后端收到的不是预期的用户名密码
  • Django后端解析方式错误:用request.POST获取JSON格式的请求数据,这在Django中无法生效

前端代码修复

Axios的post方法语法和Fetch不同:第二个参数是请求体数据,第三个参数才是请求配置(如headers、跨域凭证等)。你之前的写法导致实际发送的请求体是包含method、mode的对象,而非username和password。

修改后的React处理函数:

const handleRegister = async (e) => {
    e.preventDefault();
    try {
      // Axios post:URL + 请求体数据 + 配置选项
      const response = await axios.post(
        "http://localhost:8000/register/",
        { username, password }, // 直接传JSON对象,Axios会自动序列化
        {
          withCredentials: true, // 对应Fetch的credentials: include
          headers: {
            "Content-Type": "application/json",
          },
        }
      );

      // Axios会自动解析JSON响应,无需再调用response.json()
      setMessage(response.data.success || response.data.error);
    } catch (error) {
      setMessage("An error occurred. Please try again.");
    }
};

补充:Axios默认会把Content-Type设为application/json,这个header可以省略;withCredentials是Axios中控制跨域凭证的配置项。

后端代码修复

Django中request.POST仅能解析**表单编码(application/x-www-form-urlencoded)**的数据,而你前端发送的是JSON格式,需要从request.body中手动解析:

修改后的Django注册函数:

import json
from django.http import JsonResponse
from django.contrib.auth.models import User
from django.contrib.auth import login

def register(request):
    print(request)
    if request.method == 'POST':
        # 解析JSON格式的请求体
        try:
            data = json.loads(request.body)
        except json.JSONDecodeError:
            return JsonResponse({'error': 'Invalid JSON data'}, status=400)
        
        username = data.get('username')
        password = data.get('password')

        if not username or not password:
            return JsonResponse({'error': 'Missing username or password'}, status=400)

        try:
            user = User.objects.create_user(username=username, password=password)
            login(request, user)
            return JsonResponse({'success': 'User registered and logged in'})
        except Exception as e:
            return JsonResponse({'error': str(e)}, status=400)

    return JsonResponse({'error': 'Invalid request method'}, status=405)

如果你使用Django REST Framework,可以直接用request.data获取解析后的JSON数据,代码会更简洁。

修改后验证

调整完成后,浏览器的请求载荷会变成:

{"username":"test","password":"test"}

后端就能正确获取到用户名和密码,完成注册流程。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 22:27:04