1

Below is my frontend code i have to submit a post request from react.

const { name, email, message } = greeting;
const payload = {
  name: name,
  email: email,
  message: message,
};

console.log(payload);

fetch('http://localhost:8080/greetings', {
  method: 'POST',
  mode: 'cors',
  headers: {
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin': '*',
    // 'Content-Type': 'application/x-www-form-urlencoded',
  },

  body: JSON.stringify(payload),
})
  .then(async function (res) {
    let response = await res.json();
    console.log(response);
  })
  .catch((err) => console.log(err));

Below is my express code for post

app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));

app.post('/greetings', async (req, res) => {
  const { name, email, message } = req.body;
  console.log(req.body);
  db();
  const saveDocument = new Document({
    name: name,
    email: email,
    message: message,
  });

  await saveDocument
    .save()
    .then((savedDoc) => {
      res.send({ status: 200, mes: 'success', request: req.body });
    })
    .catch((e) => console.log(e));
});

I have tried to submit a post using postman and i was able to see data in my mongoDB. But from my frontend i always get an empty object in the request.body.

enter image description here

AngYC
  • 3,051
  • 6
  • 20

1 Answers1

2

There's 2 different types of commonly used Content-Type:

  • application/x-www-form-urlencoded
  • application/json

In Postman, you have specified to use application/x-www-form-urlencoded instead of application/json, which is why there's a mismatch between the behaviour in Postman and fetch request in React.

When you specified your request to use application/json, your Express server needs to be able to handle the parsing as well.

In Express 4.16 and above, you can use the express.json() middleware to parse your request into a JSON object to be retrieved using req.body, bodyParser (or body-parser) is deprecated. An example is as follows:

app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.post('/greetings', async (req, res) => {
  const { name, email, message } = req.body;
  console.log(req.body);
  db();
  const saveDocument = new Document({
    name: name,
    email: email,
    message: message,
  });

  await saveDocument
    .save()
    .then((savedDoc) => {
      res.send({ status: 200, mes: 'success', request: req.body });
    })
    .catch((e) => console.log(e));
});

The express.json() is a middleware to parse Content-Type: application/json, whereas express.urlencoded() is used to parse Content-Type: application/x-www-form-urlencoded


In order to test sending Content-Type: application/json in Postman, you can follow the screenshot below:

Postman Headers

Postman Body

(Screenshot source: Send POST data via raw JSON with Postman)

AngYC
  • 3,051
  • 6
  • 20
  • @NomulaLenin feel free to accept the answer by clicking on the check button next to it whenever you think this is the best answer you would get. – Youssouf Oumar Apr 29 '23 at 08:28