首页 > 解决方案 > 加载资源失败:服务器在 MERN 中响应状态为 422(无法处理的实体)

问题描述

我正在尝试制作一个 MERN 应用程序,用户可以在其中注册用户数据并将其存储在 atlas 中。但是当用户提交表单时,数据没有保存在图集中,并且在控制台中显示错误。

Failed to load resource: the server responded with a status of 422 (Unprocessable Entity)
这是我用于向服务器获取数据的 React 代码:

  const submitter = async (e) => {
    e.preventDefault();
    const { name, email, phone, work, password, cpassword } = data;

    const response = await fetch("/signup", {
      method: "POST",
      Headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        name,
        email,
        phone,
        work,
        password,
        cpassword
      }),
    });
    const res = await response.json()

    if(res.status === 422 || !res){
      window.alert("Invalid Registration")
      console.log("Invalid Registration");
    }else{
      window.alert("Registration Successful")
      console.log("Registration Successful");

      history.push("/signin")
    }
  };

问题是此代码重定向到登录页面并显示注册成功,但它没有存储我在表单中填写的数据。

我的nodejs代码:

router.post("/signup", async (req, res) => {
  const { name, email, phone, work, password, cpassword } = req.body;
  if (!name || !email || !phone || !work || !password || !cpassword) {
    return res.status(422).json({ error: "fill the form completely" });
  }
  try {
    const response = await user.findOne({ email: email });
    if (response) {
      return res.status(422).json({ err: "email already exists" });
    }
    if(password != cpassword){
      return res.status(422).json({ err: "passwords are not matching" });
    }else{
      const filldata = new user({
        name,
        email,
        phone,
        work,
        password,
        cpassword,
      });
      const data = await filldata.save(); 
      console.log(data);
  
      if (data) {
        res.status(201).json({ message: "user created succesfully" });
      } else {
        res.status(500).json({ error: "user registration failed" });
      }
    }
    
  } catch (err) {
    console.log(err);
  }
  
});

我也在"proxy": "http://localhost:3001"我的 package.json 文件中使用过

标签: node.jsreactjsmongodb

解决方案


试试这个

      if(res.status === 201){
          window.alert("Registration Successful")
          console.log("Registration Successful");
          history.push("/signin")
        }else{
        
  window.alert("Invalid Registration")
          console.log("Invalid Registration");
        }

推荐阅读