skip to Main Content

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


    • 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.
    Login or Signup to reply.
  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!");
    });
    
    Login or Signup to reply.
  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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search