skip to Main Content

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

2

Answers


  1. 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)

    Login or Signup to reply.
  2. The issue seens to be with parsing the incoming request body. You are using bodyParser.urlencoded middleware, but you need to use bodyParser.json() middleware to parse JSON-encoded request bodies.

    You can fix this by including the bodyParser.json() middleware like so:

    const express = require('express');
    const cors = require('cors');
    const bodyParser = require('body-parser');
    
    const app = express();
    
    app.use(cors());
    app.use(bodyParser.json()); // Add this line
    app.use(bodyParser.urlencoded({ extended: false }));
    
    // Rest of your code
    

    Now, you should be able to properly parse the JSON payload from the React frontend instead of getting an empty object in req.body.

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