数据未使用 NodeJS、ReactJS 保存在 MYSQL 数据库中

问题描述 投票:0回答:1

当我提交表单时,显示“查询错误”弹出窗口...数据未保存在数据库中。

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 中

javascript reactjs express axios bcrypt
1个回答
0
投票

除非您尝试发送文件,否则不要打扰

FormData
。您需要像 Multer 这样的特殊中间件来处理此类请求。

问题是,因为你没有这样的中间件,所以你所有的

req.body
属性都将是
undefined
。这导致
bcrypt.hash()
失败。

如果您还没有添加 JSON 处理中间件,只需将 JSON 处理中间件添加到您的 Express 应用程序中即可...

app.use(express.json());

并将数据作为 JSON 发送...

axios.post("http://localhost:3000/employee/add_customer", customer)
© www.soinside.com 2019 - 2024. All rights reserved.