0

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 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

You need to convert the body data to JSON before sending it in the request.

    const sendData = async () = {
    ...
    try {
        const response = await fetch("http://localhost:4000/register", {
          method: "POST",
          mode: "cors",
          headers: {
            "Content-Type": "application/json"
          },
          body: JSON.stringify({ state: "its working" })
        });
      } catch (e) {
        console.log(e);
      }
}

In your express code, you can access the state property of the request body using

app.route("/register").post((req, res) => {
  const postData = req.body.state;
  ...
  res.send("Received the data successfully!");
});

Comments

1
  • Did you set JSON parse on backend entry file?
  • Try sending the body from frontend in JSON format. You can use JSON.stringify() to encode it.
  • Check your browser console and network to confirm the requirements with data to the backend.
  • Console the req.body to check if there's anything received.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.