axios 使用NodeJS、ReactJS时数据不保存在MYSQL数据库中

31moq8wy  于 2023-11-18  发布在  iOS
关注(0)|答案(1)|浏览(108)

当我提交表格“查询错误”弹出显示.数据不保存在数据库中。
API

router.post("/add_customer", (req, res) => {
  const sql = `INSERT INTO customer (name, mobile, email, address, state, city, policytype, insurer, renewdate) VALUES (?)`;
  bcrypt.hash(req.body.password, 10, (err, hash) => {
    if (err) return res.json({ Status: false, Error: "Query Error" });
    const values = [
      req.body.name,
      req.body.mobile,
      req.body.email,
      req.body.address,
      req.body.state,
      req.body.city,
      req.body.policytype,
      req.body.insurer,
      req.file.filename,
      req.body.renewdate,
    ];
    con.query(sql, [values], (err, result) => {
      if (err) return res.json({ Status: false, Error: err });
      return res.json({ Status: true });
    });
  });
});

字符串
AXIOS API -

const [customer, setCustomer] = useState({
  name: "",
  mobile: "",
  email: "",
  address: "",
  state: "",
  city: "",
  policytype: "",
  insurer: "",
  renewdate: "",
});

const navigate = useNavigate();

const handleSubmit = (e) => {
  e.preventDefault();
  const formData = new FormData();
  formData.append("name", customer.name);
  formData.append("mobile", customer.mobile);
  formData.append("email", customer.email);
  formData.append("address", customer.address);
  formData.append("state", customer.state);
  formData.append("city", customer.city);
  formData.append("policytype", customer.policytype);
  formData.append("insurer", customer.insurer);
  formData.append("renewdate", customer.renewdate);

  axios
    .post("http://localhost:3000/employee/add_customer", formData)
    .then((result) => {
      if (result.data.Status) {
        navigate("/employeedashboard/customer");
      } else {
        alert(result.data.Error);
      }
    });
};


代码在NodeJs和ReactJs中

jei2mxaa

jei2mxaa1#

除非你想发送文件,否则不要使用FormData,你需要像Multer这样的特殊中间件来处理mutlipart/form-data请求体。
问题是,由于没有这样的中间件,所有的req.body属性都将是undefined,这导致bcrypt.hash()失败。
简单地添加JSON处理中间件到您的Express应用程序,如果你还没有.

app.use(express.json());

字符串
并以JSON格式发送数据。

axios.post("http://localhost:3000/employee/add_customer", customer)


进一步的建议...永远不要忽略错误。至少,记录它们

bcrypt.hash(req.body.password, 10, (err, hash) => {
  if (err) {
    console.error("hash failed for", req.body.password, err);
    return res.status(400).send("Password could not be hashed");
  }

相关问题