使用Formik时React表单数据无法传递到Node.js求助
解决Formik表单数据无法从React传递到Node.js的问题
一、React端代码的核心问题及修正
你的代码存在几个关键问题,导致Formik无法收集输入数据并传递到Node服务:
1. 表单元素未与Formik绑定
所有输入、单选、下拉元素都未设置name属性(需与Formik initialValues里的字段名完全一致),也未绑定formik.handleChange和formik.value,导致Formik无法捕获用户输入。
2. 请求URL格式错误
axios请求的URL写成了http:localhost:5000/api/detailsnewform,正确格式应为http://localhost:5000/api/detailsnewform(缺少双斜杠)。
3. 未定义loading状态
代码中使用了setloading但未声明对应的state,会触发运行时错误。
4. 冗余代码
apple函数未被调用,属于无效代码,可直接删除。
修正后的React代码
import * as yup from "yup"; import { useFormik } from "formik"; import { useState } from "react"; const formValidation = yup.object({ NameoftheUPSIProject: yup .string() .required("Fill the Name of the UPSI Project"), InformationSharedBy: yup.string().required("Fill the Information Shared By"), InfoSharedwithrespectto: yup.string().required("A radio option is required"), InsiderTypes: yup.string().required("Fill the Insider Types"), ContactPerson: yup.string().required("Fill the Contact Person"), NameoftheOrganization: yup .string() .required("Fill the Name of the Organization"), DateofSharing: yup.string().required("Fill the Date and Time of Sharing"), ParticularofInformationShared: yup .string() .required("Fill the Particular of Information Shared"), PurposeofSharing: yup.string().required("Fill the Purpose of Sharing"), ModeofSharing: yup.string().required("Fill the Mode of Sharing"), }); const DetailsList = () => { const [loading, setloading] = useState(false); const formik = useFormik({ initialValues: { NameoftheUPSIProject: "", InformationSharedBy: "", InfoSharedwithrespectto: "", InsiderTypes: "", ContactPerson: "", NameoftheOrganization: "", DateofSharing: "", ParticularofInformationShared: "", PurposeofSharing: "", ModeofSharing: "", }, validationSchema: formValidation, onSubmit: async (values) => { console.log("提交的数据:", values); try { setloading(true); await axios.post(`http://localhost:5000/api/detailsnewform`, values); setloading(false); alert("Form Created Successfully"); formik.resetForm(); } catch (error) { console.error("提交失败:", error); setloading(false); } }, }); return ( <form onSubmit={formik.handleSubmit}> <div> <div> <div className="mb-3 row"> <label className="col-sm-2 col-form-label"> Name of the UPSI Project: </label> <div className="col-sm-10"> <input type="text" className="form-control" name="NameoftheUPSIProject" value={formik.values.NameoftheUPSIProject} onChange={formik.handleChange} onBlur={formik.handleBlur} /> {formik.touched.NameoftheUPSIProject && formik.errors.NameoftheUPSIProject && ( <div style={{ color: "red" }}>{formik.errors.NameoftheUPSIProject}</div> )} </div> </div> <div className="mb-3 row"> <label className="col-sm-2 col-form-label"> Information Shared By: </label> <div className="col-sm-10"> <input type="text" className="form-control" name="InformationSharedBy" value={formik.values.InformationSharedBy} onChange={formik.handleChange} onBlur={formik.handleBlur} /> {formik.touched.InformationSharedBy && formik.errors.InformationSharedBy && ( <div style={{ color: "red" }}>{formik.errors.InformationSharedBy}</div> )} </div> </div> <div className="mb-3 row"> <label className="col-sm-2 col-form-label"> Info Shared with respect to: </label> <div className="col-sm-10"> <div> <input type="radio" name="InfoSharedwithrespectto" value="Designated Person" checked={formik.values.InfoSharedwithrespectto === "Designated Person"} onChange={formik.handleChange} onBlur={formik.handleBlur} /> Designated Person </div> <div> <input type="radio" name="InfoSharedwithrespectto" value="Insider" checked={formik.values.InfoSharedwithrespectto === "Insider"} onChange={formik.handleChange} onBlur={formik.handleBlur} /> Insider </div> <div> <input type="radio" name="InfoSharedwithrespectto" value="UPSI Project" checked={formik.values.InfoSharedwithrespectto === "UPSI Project"} onChange={formik.handleChange} onBlur={formik.handleBlur} /> UPSI Project </div> {formik.touched.InfoSharedwithrespectto && formik.errors.InfoSharedwithrespectto && ( <div style={{ color: "red" }}>{formik.errors.InfoSharedwithrespectto}</div> )} </div> </div> <div className="mb-3 row"> <label className="col-sm-2 col-form-label"> Insider Types: </label> <div className="col-sm-10"> <select className="form-select form-select-lg mb-3" aria-label=".form-select-lg example" name="InsiderTypes" value={formik.values.InsiderTypes} onChange={formik.handleChange} onBlur={formik.handleBlur} > <option value="Director">Director</option> <option value="Managing Director">Managing Director</option> <option value="Independent Director">Independent Director</option> <option value="CFO">CFO</option> <option value="Company Secretary">Company Secretary</option> </select> {formik.touched.InsiderTypes && formik.errors.InsiderTypes && ( <div style={{ color: "red" }}>{formik.errors.InsiderTypes}</div> )} </div> </div> </div> <div className="mb-3 row"> <label className="col-sm-2 col-form-label"> Insider Signed Confidentially Agreement: </label> <div className="col-sm-10"> <label className="col-sm-2 col-form-label" style={{ color: "red" }} > No Confidentially Agreement Signed </label> </div> </div> <div className="mb-3 row"> <label className="col-sm-2 col-form-label"> Contact Person: </label> <div className="col-sm-10"> <input type="text" className="form-control" name="ContactPerson" value={formik.values.ContactPerson} onChange={formik.handleChange} onBlur={formik.handleBlur} /> {formik.touched.ContactPerson && formik.errors.ContactPerson && ( <div style={{ color: "red" }}>{formik.errors.ContactPerson}</div> )} </div> </div> <div className="mb-3 row"> <label className="col-sm-2 col-form-label"> Type of Organization: </label> <div className="col-sm-10"> <label className="col-sm-2 col-form-label"> Partnership </label> </div> </div> <div className="mb-3 row"> <label className="col-sm-2 col-form-label"> Name of the Organization: </label> <div className="col-sm-10"> <input type="text" className="form-control" name="NameoftheOrganization" value={formik.values.NameoftheOrganization} onChange={formik.handleChange} onBlur={formik.handleBlur} /> {formik.touched.NameoftheOrganization && formik.errors.NameoftheOrganization && ( <div style={{ color: "red" }}>{formik.errors.NameoftheOrganization}</div> )} </div> </div> <div className="mb-3 row"> <label className="col-sm-2 col-form-label"> Date and Time of Sharing: </label> <div className="col-sm-10"> <input type="date" name="DateofSharing" value={formik.values.DateofSharing} onChange={formik.handleChange} onBlur={formik.handleBlur} /> {formik.touched.DateofSharing && formik.errors.DateofSharing && ( <div style={{ color: "red" }}>{formik.errors.DateofSharing}</div> )} </div> </div> <div className="mb-3 row"> <label className="col-sm-2 col-form-label"> Particular of Information Shared: </label> <div className="col-sm-10"> <input type="text" className="form-control" name="ParticularofInformationShared" value={formik.values.ParticularofInformationShared} onChange={formik.handleChange} onBlur={formik.handleBlur} /> {formik.touched.ParticularofInformationShared && formik.errors.ParticularofInformationShared && ( <div style={{ color: "red" }}>{formik.errors.ParticularofInformationShared}</div> )} </div> </div> <div className="mb-3 row"> <label className="col-sm-2 col-form-label"> Purpose of Sharing: </label> <div className="col-sm-10"> <input type="text" className="form-control" name="PurposeofSharing" value={formik.values.PurposeofSharing} onChange={formik.handleChange} onBlur={formik.handleBlur} /> {formik.touched.PurposeofSharing && formik.errors.PurposeofSharing && ( <div style={{ color: "red" }}>{formik.errors.PurposeofSharing}</div> )} </div> </div> <div className="mb-3 row"> <label className="col-sm-2 col-form-label"> Mode of Sharing: </label> <div className="col-sm-10"> <select className="form-select form-select-lg mb-3" aria-label=".form-select-lg example" name="ModeofSharing" value={formik.values.ModeofSharing} onChange={formik.handleChange} onBlur={formik.handleBlur} > <option value="Email">Email</option> <option value="Physical">Physical</option> <option value="Pendrive">Pendrive</option> </select> {formik.touched.ModeofSharing && formik.errors.ModeofSharing && ( <div style={{ color: "red" }}>{formik.errors.ModeofSharing}</div> )} <div className="mb-3 row"> <button type="submit" className="button" disabled={loading}> {loading ? "Submitting..." : "SUBMIT"} </button> </div> </div> </div> </div> </form> ); }; export default DetailsList;
二、Node.js端需要的接收代码
要完成数据传递,Node端需配置对应的POST接口接收数据,以下是Express框架的示例:
1. 安装依赖
npm install express cors body-parser
2. 编写接口代码
const express = require('express'); const cors = require('cors'); const bodyParser = require('body-parser'); const app = express(); const port = 5000; // 中间件配置 app.use(cors()); app.use(bodyParser.json()); // 表单数据接收接口 app.post('/api/detailsnewform', (req, res) => { const formData = req.body; console.log('收到的表单数据:', formData); // 在这里编写数据库存储逻辑(示例为MongoDB) // db.collection('forms').insertOne(formData, (err) => { // if (err) return res.status(500).json({ error: '存储失败' }); // res.status(200).json({ message: '存储成功' }); // }); // 临时返回成功响应 res.status(200).json({ message: '数据接收成功' }); }); app.listen(port, () => { console.log(`Server running on http://localhost:${port}`); });
三、验证步骤
- 启动Node服务器,确认其在5000端口运行。
- 启动React项目,填写表单并提交。
- 查看Node端控制台是否收到数据,同时检查React端控制台有无错误。
内容的提问来源于stack exchange,提问作者arasu ramanan
相关产品推荐
相关产品推荐

