Home > Net >  I can't access the res.body of a POST request from the express server in a react/express stack
I can't access the res.body of a POST request from the express server in a react/express stack

Time:01-21

This is the server code:

app.post("/hello", async function (req, res) {
  let passedInToggleValue = false
  console.log(req.body);
  if (req.body === null || req.body === undefined) {
    console.log("body is empty");
  }
  else if (!req.body.hasOwnProperty('switchBool')) {
    console.log("switchBool is empty");
  }
  else if (req.body.switchBool) {
    passedInToggleValue = true
  }
  const toggleValue = passedInToggleValue ? "on" : "off";
  const resData = `this backend is running and the Testing On/Off Switch is ${toggleValue}`;
  res.send(resData);
});

And this is the react code that calls the express API:

async function callApi() {
  const url = `${process.env.REACT_APP_API_URL}/hello`;
  const requestOptions = {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ switchBool: true })
  };
  const helloStream = await fetch(url, requestOptions);
  const helloText = await helloStream.text();
  console.log(helloText as string);
}

But in the terminal, console.log(req.body); shows up as undefined and if (req.body === null || req.body === undefined) gets triggered and "body is empty" appears in my terminal.

CodePudding user response:

I added app.use(express.json()); to the express server code so the relevant section looks like this now:

app.use(express.json());

app.post("/hello", async function (req, res) {
  let passedInToggleValue = false
  console.log(req.body);
  if (req.body === null || req.body === undefined) {
    console.log("body is empty");
  }
  else if (!req.body.hasOwnProperty('switchBool')) {
    console.log("switchBool is empty");
  }
  else if (req.body.switchBool) {
    passedInToggleValue = true
  }
  const toggleValue = passedInToggleValue ? "on" : "off";
  const resData = `this backend is running and the Testing On/Off Switch is ${toggleValue}`;
  res.send(resData);
});
  • Related