I am trying to send a object from react to express using fetch api. I have added the data to post request. the express server is unable to receive any request made to it.
React Code:
const sendData = async ()=>{
try{
const response = await fetch("http://localhost:4000/register",{method:"POST",mode:"cors",body:{"state":"its working"}});
}
catch(e){
console.log(e)
}
}
useEffect(() => {
console.log("Effect started");
sendData();
}, [user]);
Express code
app.route("/register").post((req,res)=>{
const postData = req.body.state;
console.log(postData);
});
Kindly help. I am not sure why it is not able to log anything in serverside.
3
Answers
JSON.stringify()
to encode it.req.body
to check if there’s anything received.You need to convert the body data to JSON before sending it in the request.
In your express code, you can access the state property of the request body using
In React App (frontend): add the headers property as following:
js headers: { 'Content-Type': 'application/json' }
in the api call function.In Express App (backend): add the middleware as following:
js app.use(express.json());
which help to parse the json body.