I am working on React Project, currently making a signup form.
Posting Form Data using Form works fine. But when i use onSubmit={handleSubmit}and use fetch API's like axios or just fetch, it stuck at axios.post(url,options). I actually need to Post Users data and if User already exist than need to print error message at client side.
Register Component 1:
<Form method='POST' action="http://localhost:5000/api/register">
<Form.Group controlId="validationCustom01">
<Form.Label>Full Name</Form.Label>
<Form.Control
type="text"
placeholder="Full Name"
/>
<Form.Control.Feedback>Looks good!</Form.Control.Feedback>
</Form.Group>
<Form.Group controlId="validationCustomUsername">
<Form.Label>Username</Form.Label>
<InputGroup >
<Form.Control
type="email"
placeholder="Email"
name="email"
/>
</InputGroup>
</Form.Group>
<Form.Group controlId="validationCustom04">
<Form.Label>Password</Form.Label>
<Form.Control
type="password"
placeholder="Password"
name="password" />
</Form.Group>
<Button type="submit" className='button bg-success' >Submit</Button>
</Form>
Server.js
app.post('/api/register', async (req,res) =>
{
let {name,email,password} =req.body
if(password.length >=8 )
{
let hashpassword = await bcrypt.hash(password,10);
pool.query(`SELECT * FROM USERSDATA WHERE EMAIL= $1 `, [email],
(err,results) =>
{
if(err){
throw err;
};
if(results.rows.length == 0)
{
pool.query(`INSERT INTO USERSDATA (NAME,EMAIL,PASSWORD) VALUES ($1,$2,$3) RETURNING id`,[name,email,hashpassword],
(err,results) =>
{
if(err)
{
throw error;
}
res.redirect("http://localhost:3000/login");
}
);
}
else{
res.status(400)
//Here i want to send error as response and to process this error at frontend
res.redirect("http://localhost:3000/register")
}
}
);
}
});
i tried to handle the Form submit using handleSubmit and made different fetch post requests but got different type of error while playing with the code. One of technique i used is given.
const handleSubmit = async e => {
e.preventDefault()
const options = {
method: "POST",
body:JSON.stringify(data),
headers:{
'Content-Type':'application/json'}}
const res = await axios.post('/api/register', options)
// here (above) i got many errors while playing different techniques like different fetch API's
}}
return(
<Form onSubmit={handleSubmit} >
...
...
</Form>
)
Is there any other way i can access server response message in React Component? As this took my 8 hours and still is unsolved.