ReactJS post request不向Django后端发送值

2fjabf4q  于 12个月前  发布在  React
关注(0)|答案(2)|浏览(288)

我有一个React前端组件,用于登录/帐户创建。我面临的问题是,当试图注册一个新用户,我得到了一个错误的请求。在后端打印请求后,我看到的请求为<WSGIRequest: POST '/register/'>
下面是我的react函数:

const handleRegister = async (e) => {
    e.preventDefault();
    try {
      const response = await axios.post("http://localhost:8000/register/", {
        method: "POST",
        mode: "cors",
        credentials: "include",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ username, password }),
      });

      const data = await response.json();
      setMessage(data.success || data.error);
    } catch (error) {
      setMessage("An error occurred. Please try again.");
    }
  };

这是我的Django函数:

def register(request):
    print(request)
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.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)

这是我从浏览器请求的有效负载:

{
  "method": "POST",
  "mode": "cors",
  "credentials": "include",
  "headers": {
    "Content-Type": "application/json"
  },
  "body": "{\"username\":\"test\",\"password\":\"test\"}"
}

响应:{"error": "Missing username or password"}
不知道我错过了什么,使它的价值观之间丢失前端到后端..
我已经从fetch切换到axios,看看这是否是我的问题。我已经在www.example.com中安装/启用了CORSSettings.py

zsohkypk

zsohkypk1#

试试这个你发送的是一个组合对象代替body

const handleRegister = async (e) => {
          e.preventDefault();
          try {
            const response = await axios.post("http://localhost:8000/register/", {
              username,
              password
            }, {
              headers: {
                "Content-Type": "application/json",
              },
              withCredentials: true
            });
        
            const data = response.data;
            setMessage(data.success || data.error);
          } catch (error) {
            setMessage("An error occurred. Please try again.");
          }
        };
f5emj3cl

f5emj3cl2#

我用的是Django 4。要在Django中接受JSON数据,您需要在代码中调整一些事情。
首先,正如Ruzaik Nazeer所提到的,您将Axios的设置与请求中的帖子数据相结合。使用axios.post调用API的正确格式如下:

axios.post(url, data, axiosConfiguration)

你可以参考官方的axios文档来获得更多的细节和例子:axios documentation
要使请求按您希望的方式工作,我们需要调整您的代码,如下所示:

const handleRegister = async (e) => {
  e.preventDefault();
  const response = await axios.post(
    "http://127.0.0.1:8000/register/",
    {
      username,
      password,
    },
    {
      mode: "cors",
      credentials: "include",
      headers: {
        "Content-Type": "multipart/form-data",
      },
    }
  );
};

请注意,当使用"Content-Type": "application/json"时,您无法通过django中的request.POST访问数据。相反,您需要使用"Content-Type": "multipart/form-data"作为头文件。
axios.post请求中的headers对象现在包含"Content-Type": "multipart/form-data"标头。这允许您通过request.POST.get('username')访问服务器端的数据。
服务器端的Django代码可以保持不变。

相关问题