I’m doing a form filling project that stores data from react to nodejs and then to database. I am unable to pass the data from react to node

huangapple go评论59阅读模式
英文:

I’m doing a form filling project that stores data from react to nodejs and then to database. I am unable to pass the data from react to node

问题

这是您提供的代码段,用于将数据从React传递到Node.js,然后存储到数据库中。请问您需要关于这段代码的帮助或有特定的问题吗?

英文:

I’m doing a form filling project that stores data from react to nodejs and then to database. I am unable to pass the data from react to node when using FORMIK I need to know what extra should I code to solve the issue
my code for your reference :

Please find the following code with the issue.

import * as yup from "yup";
import { useFormik } from "formik";
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 apple = (data) => {
console.log(data);
fetch(`localhost:5000/details`, {
method: "POST",
body: JSON.stringify(data),
headers: { "Content-Type": "application/json" },
});
};
const DetailsList = () => {
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.log(error);
}
},
});
return (
<form onSubmit={formik.handleSubmit}>
<div>
<div>
{/* <div class="mb-3 row">
<label for="staticEmail" class="col-sm-2 col-form-label">Email</label>
<div class="col-sm-10">
<input type="text" class="form-control-plaintext" id="staticEmail" value="email@example.com"/>
</div> */}
<div class="mb-3 row">
<label for="text" class="col-sm-2 col-form-label">
Name of the UPSI Project:
</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputPassword" />
</div>
</div>
<div class="mb-3 row">
<label for="inputPassword" class="col-sm-2 col-form-label">
Information Shared By:
</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputPassword" />
</div>
</div>
<div class="mb-3 row">
<label for="text" class="col-sm-2 col-form-label">
Info Shared with respect to:
</label>
<div class="col-sm-10">
<input type="radio" name="reason" value="Fit Description" />
Designated Person
<div>
<input type="radio" name="reason" value="Fit Description" />
Insider
</div>
<div>
<input type="radio" name="reason" value="Fit Description" />
UPSI Project
</div>
</div>
</div>
<div class="mb-3 row">
<label for="text" class="col-sm-2 col-form-label">
Insider Types:
</label>
<div class="col-sm-10">
<select
class="form-select form-select-lg mb-3"
aria-label=".form-select-lg example"
>
<option selected>Director</option>
<option value="1">Managing Director</option>
<option value="2">Independent Director</option>
<option value="3">CFO</option>
<option value="4">Company Secretary</option>
</select>
</div>
</div>
</div>
<div class="mb-3 row">
<label for="text" class="col-sm-2 col-form-label">
Insider Signed Confidentially Agreement:
</label>
<div class="col-sm-10">
<label
for="text"
class="col-sm-2 col-form-label"
style={{ color: "red" }}
>
No Confidentially Agreement Signed
</label>
</div>
</div>
<div class="mb-3 row">
<label for="text" class="col-sm-2 col-form-label">
Contact Person:
</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputPassword" />
</div>
<div class="mb-3 row">
<label for="text" class="col-sm-2 col-form-label">
Type of Organization:
</label>
<div class="col-sm-10">
<label for="text" class="col-sm-2 col-form-label">
Partnership
</label>
</div>
</div>
<div class="mb-3 row">
<label for="text" class="col-sm-2 col-form-label">
Name of the Organization:
</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputPassword" />
</div>
</div>
<div class="mb-3 row">
<label for="text" class="col-sm-2 col-form-label">
Date and Time of Sharing:
</label>
<div class="col-sm-10">
<input type="date" id="date" name="trip-start" />
<script src="date.js"></script>
</div>
</div>
<div class="mb-3 row">
<label for="text" class="col-sm-2 col-form-label">
Particular of Information Shared:
</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputPassword" />
</div>
</div>
<div class="mb-3 row">
<label for="text" class="col-sm-2 col-form-label">
Purpose of Sharing:
</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputPassword" />
</div>
<div class="mb-3 row">
<label for="text" class="col-sm-2 col-form-label">
Mode of Sharing:
</label>
<div class="col-sm-10">
<select
class="form-select form-select-lg mb-3"
aria-label=".form-select-lg example"
>
<option selected>Email</option>
<option value="1">Physical</option>
<option value="2">Pendrive</option>
</select>
<div class="mb-3 row">
{/* <input type="submit" value="Submit"/> */}
<button type="submit" className="button">
SUBMIT
</button>
</div>
</div>
</div>
</div>
</div>
</div>
<script></script>
</form>
);
};
export default DetailsList;

I tried using above code but unable to pass the data

答案1

得分: 1

Here is the translated code part:

这是使用formik的示例

import React from 'react';
import { Formik, Form, Field, ErrorMessage } from 'formik';
import * as Yup from 'yup';
import { Button, Grid, Typography, FormControl, InputLabel, Input, FormHelperText } from '@mui/material';

const SignupForm = () => {
  return (
    <div>
      <Typography variant='h4' align='center' gutterBottom>
        注册
      </Typography>
      <Formik
        initialValues={{
          firstName: '',
          lastName: '',
          email: '',
          password: '',
          confirmPassword: '',
          address: '',
          phone: '',
        }}
        validationSchema={Yup.object({
          firstName: Yup.string().required('名字不能为空'),
          lastName: Yup.string().required('姓氏不能为空'),
          email: Yup.string().email('无效的电子邮件地址').required('电子邮件不能为空'),
          password: Yup.string()
            .required('密码不能为空')
            .min(8, '密码太短,应至少为8个字符')
            .matches(
              /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/,
              '密码必须包含至少一个大写字母、一个小写字母、一个数字和一个特殊字符',
            ),
          confirmPassword: Yup.string()
            .oneOf([Yup.ref('password'), null], '密码必须匹配')
            .required('确认密码不能为空'),
          address: Yup.string().required('地址不能为空'),
          phone: Yup.string()
            .matches(/^\+?\d{10,14}$/, '无效的电话号码')
            .required('电话号码不能为空'),
        })}
        onSubmit={(values, { setSubmitting }) => {
          setTimeout(() => {
            alert(JSON.stringify(values, null, 2));
            setSubmitting(false);
          }, 400);
        }}
      >
        {({ errors, touched, isSubmitting }) => (
          <Form>
            <Grid container spacing={2}>
              <Grid item xs={12} sm={6}>
                <FormControl fullWidth error={touched.firstName && !!errors.firstName}>
                  <InputLabel htmlFor='firstName'>名字</InputLabel>
                  <Field as={Input} id='firstName' name='firstName' variant='outlined' />
                  <FormHelperText>
                    <ErrorMessage name='firstName' />
                  </FormHelperText>
                </FormControl>
              </Grid>
              <Grid item xs={12} sm={6}>
                <FormControl fullWidth error={touched.lastName && !!errors.lastName}>
                  <InputLabel htmlFor='lastName'>姓氏</InputLabel>
                  <Field as={Input} id='lastName' name='lastName' variant='outlined' />
                  <FormHelperText>
                    <ErrorMessage name='lastName' />
                  </FormHelperText>
                </FormControl>
              </Grid>
              <Grid item xs={12}>
                <FormControl fullWidth error={touched.email && !!errors.email}>
                  <InputLabel htmlFor='email'>电子邮件</InputLabel>
                  <Field as={Input} id='email' name='email' type='email' variant='outlined' />
                  <FormHelperText>
                    <ErrorMessage name='email' />
                  </FormHelperText>
                </FormControl>
              </Grid>
              <Grid item xs={12}>
                <FormControl fullWidth error={touched.password && !!errors.password}>
                  <InputLabel htmlFor='password'>密码</InputLabel>
                  <Field as={Input} id='password' name='password' type='password' variant='outlined' />
                  <FormHelperText>
                    <ErrorMessage name='password' />
                  </FormHelperText>
                </FormControl>
              </Grid>
              <Grid item xs={12}>
                <FormControl fullWidth error={touched.confirmPassword && !!errors.confirmPassword}>
                  <InputLabel htmlFor='confirmPassword'>确认密码</InputLabel>
                  <Field as={Input} id='confirmPassword' name='confirmPassword' type='password' variant='outlined' />
                  <FormHelperText>
                    <ErrorMessage name='confirmPassword' />
                  </FormHelperText>
                </FormControl>
              </Grid>
              <Grid item xs={12}>
                <FormControl fullWidth error={touched.address && !!errors.address}>
                  <InputLabel htmlFor='address'>地址</InputLabel>
                  <Field as={Input} id='address' name='address' variant='outlined' />
                  <FormHelperText>
                    <ErrorMessage name='address' />
                  </FormHelperText>
                </FormControl>
              </Grid>
              <Grid item xs={12}>
                <FormControl fullWidth error={touched.phone && !!errors.phone}>
                  <InputLabel htmlFor='phone'>电话号码</InputLabel>
                  <Field as={Input} id='phone' name='phone' variant='outlined' />
                  <FormHelperText>
                    <ErrorMessage name='phone' />
                  </FormHelperText>
                </FormControl>
              </Grid>
              <Grid item xs={12}>
                <Button variant='contained' color='primary' type='submit' disabled={isSubmitting}>
                  提交
                </Button>
              </Grid>
            </Grid>
          </Form>
        )}
      </Formik>
    </div>
  );
};

export default SignupForm;

Please note that I've translated the comments and error messages in the code.

英文:

This is an example of using formik

import React from &#39;react&#39;;
import { Formik, Form, Field, ErrorMessage } from &#39;formik&#39;;
import * as Yup from &#39;yup&#39;;
import { Button, Grid, Typography, FormControl, InputLabel, Input, FormHelperText } from &#39;@mui/material&#39;;
const SignupForm = () =&gt; {
return (
&lt;div&gt;
&lt;Typography variant=&#39;h4&#39; align=&#39;center&#39; gutterBottom&gt;
Signup
&lt;/Typography&gt;
&lt;Formik
initialValues={{
firstName: &#39;&#39;,
lastName: &#39;&#39;,
email: &#39;&#39;,
password: &#39;&#39;,
confirmPassword: &#39;&#39;,
address: &#39;&#39;,
phone: &#39;&#39;,
}}
validationSchema={Yup.object({
firstName: Yup.string().required(&#39;First name is required&#39;),
lastName: Yup.string().required(&#39;Last name is required&#39;),
email: Yup.string().email(&#39;Invalid email address&#39;).required(&#39;Email is required&#39;),
password: Yup.string()
.required(&#39;Password is required&#39;)
.min(8, &#39;Password is too short - should be 8 characters or longer&#39;)
.matches(
/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&amp;])[A-Za-z\d@$!%*?&amp;]{8,}$/,
&#39;Password must contain at least one uppercase letter, one lowercase letter, one number, and one special character&#39;,
),
confirmPassword: Yup.string()
.oneOf([Yup.ref(&#39;password&#39;), null], &#39;Passwords must match&#39;)
.required(&#39;Confirm password is required&#39;),
address: Yup.string().required(&#39;Address is required&#39;),
phone: Yup.string()
.matches(/^\+?\d{10,14}$/, &#39;Invalid phone number&#39;)
.required(&#39;Phone number is required&#39;),
})}
onSubmit={(values, { setSubmitting }) =&gt; {
setTimeout(() =&gt; {
alert(JSON.stringify(values, null, 2));
setSubmitting(false);
}, 400);
}}
&gt;
{({ errors, touched, isSubmitting }) =&gt; (
&lt;Form&gt;
&lt;Grid container spacing={2}&gt;
&lt;Grid item xs={12} sm={6}&gt;
&lt;FormControl fullWidth error={touched.firstName &amp;&amp; !!errors.firstName}&gt;
&lt;InputLabel htmlFor=&#39;firstName&#39;&gt;First Name&lt;/InputLabel&gt;
&lt;Field as={Input} id=&#39;firstName&#39; name=&#39;firstName&#39; variant=&#39;outlined&#39; /&gt;
&lt;FormHelperText&gt;
&lt;ErrorMessage name=&#39;firstName&#39; /&gt;
&lt;/FormHelperText&gt;
&lt;/FormControl&gt;
&lt;/Grid&gt;
&lt;Grid item xs={12} sm={6}&gt;
&lt;FormControl fullWidth error={touched.lastName &amp;&amp; !!errors.lastName}&gt;
&lt;InputLabel htmlFor=&#39;lastName&#39;&gt;Last Name&lt;/InputLabel&gt;
&lt;Field as={Input} id=&#39;lastName&#39; name=&#39;lastName&#39; variant=&#39;outlined&#39; /&gt;
&lt;FormHelperText&gt;
&lt;ErrorMessage name=&#39;lastName&#39; /&gt;{&#39; &#39;}
&lt;/FormHelperText&gt;
&lt;/FormControl&gt;
&lt;/Grid&gt;
&lt;Grid item xs={12}&gt;
&lt;FormControl fullWidth error={touched.email &amp;&amp; !!errors.email}&gt;
&lt;InputLabel htmlFor=&#39;email&#39;&gt;Email&lt;/InputLabel&gt;
&lt;Field as={Input} id=&#39;email&#39; name=&#39;email&#39; type=&#39;email&#39; variant=&#39;outlined&#39; /&gt;
&lt;FormHelperText&gt;
&lt;ErrorMessage name=&#39;email&#39; /&gt;
&lt;/FormHelperText&gt;
&lt;/FormControl&gt;
&lt;/Grid&gt;
&lt;Grid item xs={12}&gt;
&lt;FormControl fullWidth error={touched.password &amp;&amp; !!errors.password}&gt;
&lt;InputLabel htmlFor=&#39;password&#39;&gt;Password&lt;/InputLabel&gt;
&lt;Field as={Input} id=&#39;password&#39; name=&#39;password&#39; type=&#39;password&#39; variant=&#39;outlined&#39; /&gt;
&lt;FormHelperText&gt;
&lt;ErrorMessage name=&#39;password&#39; /&gt;
&lt;/FormHelperText&gt;
&lt;/FormControl&gt;
&lt;/Grid&gt;
&lt;Grid item xs={12}&gt;
&lt;FormControl fullWidth error={touched.confirmPassword &amp;&amp; !!errors.confirmPassword}&gt;
&lt;InputLabel htmlFor=&#39;confirmPassword&#39;&gt;Confirm Password&lt;/InputLabel&gt;
&lt;Field as={Input} id=&#39;confirmPassword&#39; name=&#39;confirmPassword&#39; type=&#39;password&#39; variant=&#39;outlined&#39; /&gt;
&lt;FormHelperText&gt;
&lt;ErrorMessage name=&#39;confirmPassword&#39; /&gt;
&lt;/FormHelperText&gt;
&lt;/FormControl&gt;
&lt;/Grid&gt;
&lt;Grid item xs={12}&gt;
&lt;FormControl fullWidth error={touched.address &amp;&amp; !!errors.address}&gt;
&lt;InputLabel htmlFor=&#39;address&#39;&gt;Address&lt;/InputLabel&gt;
&lt;Field as={Input} id=&#39;address&#39; name=&#39;address&#39; variant=&#39;outlined&#39; /&gt;
&lt;FormHelperText&gt;
&lt;ErrorMessage name=&#39;address&#39; /&gt;
&lt;/FormHelperText&gt;
&lt;/FormControl&gt;
&lt;/Grid&gt;
&lt;Grid item xs={12}&gt;
&lt;FormControl fullWidth error={touched.phone &amp;&amp; !!errors.phone}&gt;
&lt;InputLabel htmlFor=&#39;phone&#39;&gt;Phone&lt;/InputLabel&gt;
&lt;Field as={Input} id=&#39;phone&#39; name=&#39;phone&#39; variant=&#39;outlined&#39; /&gt;
&lt;FormHelperText&gt;
&lt;ErrorMessage name=&#39;phone&#39; /&gt;
&lt;/FormHelperText&gt;
&lt;/FormControl&gt;
&lt;/Grid&gt;
&lt;Grid item xs={12}&gt;
&lt;Button variant=&#39;contained&#39; color=&#39;primary&#39; type=&#39;submit&#39; disabled={isSubmitting}&gt;
Submit
&lt;/Button&gt;
&lt;/Grid&gt;
&lt;/Grid&gt;
&lt;/Form&gt;
)}
&lt;/Formik&gt;
&lt;/div&gt;
);
};
export default SignupForm;

Then inside the onSubmit function you can call the backend.

here you can find the repo https://github.com/radika-insfra/formik-sample

I've checked your code the axios call should be like this,

  axios
.post(`http:localhost:5000/api/detailsnewform`, values)
.then((response) =&gt; {
console.log(response.data);
})
.catch((e) =&gt; {
console.log(e)
});

if you need help in nodejs side, please have a comment.

huangapple
  • 本文由 发表于 2023年5月11日 14:17:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76224659.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定