how to send post from data from react and capture the data in express

react code
const [formDetails,setFormDetails]=useState({
name : '',
mail:'',
password:''
});

async function HandleForm(e){
e.preventDefault()
console.log("inside fetch fn")
try{
let res=await fetch('http://localhost:4040/register',{
method:'POST',
body:formDetails,
headers:{
"Content-type":"application/json"
}
});
console.log("inside try block")
}
catch(err){
console.log(err)
}

}

<form onSubmit={HandleFrom}>
<input type="submit" />
</form>
const [formDetails,setFormDetails]=useState({
name : '',
mail:'',
password:''
});

async function HandleForm(e){
e.preventDefault()
console.log("inside fetch fn")
try{
let res=await fetch('http://localhost:4040/register',{
method:'POST',
body:formDetails,
headers:{
"Content-type":"application/json"
}
});
console.log("inside try block")
}
catch(err){
console.log(err)
}

}

<form onSubmit={HandleFrom}>
<input type="submit" />
</form>
express codE:
routes.post('/register',async(req,res)=>{
const receivedData=req.body;
console.log(receivedData)
}
routes.post('/register',async(req,res)=>{
const receivedData=req.body;
console.log(receivedData)
}
3 Replies
vic
vicOP4mo ago
the problem in react code , the try block is not executing and catch blockis also not executing ... and in express it shows 'undefined' value Console Logs inside fetch fn but not inside try block
Joao
Joao4mo ago
This looks like an incomplete example, I'm guessing that the component code is incorrect and the JavaScript code doesn't run to completion, running into an error. As an aside, do not use capital letters when defining functions. Specially in React, which requires components to be in upper case. I don't know if this is the issue here, or even if it's an issue at all when dealing with functions declared inside components, but it's just good practice.
vic
vicOP4mo ago
I'm sorry , i forget to close this post , the error is actually I use cors , express.json, urlencoded on controller file not on main server.js file
Want results from more Discord servers?
Add your server