How to send form data from React to the Node JS back end server

I am trying to send the FormData from React JS to the backend (express node server) as shown below.

I am seeing the empty value for req.body.myFormData (expressTest.js).
I tried the suggestions from this post too but no luck. Any help is appreciated.

how do i send FormData to the node server from React js axios post request?

reactTest.js module

myFormData = new FormData();
myFormData.append("userName","testuser")
//myFormData.append("file", file) //eventually sending the file once it works
export const sendDocument = async (myFormData) => {
  return await axios({
    method: 'post',
    url: `/sendDocument`,
    data: myFormData,
    headers: { 'Content-Type': 'multipart/form-data' }
  });
};

expressTest.js

const express = require('express')
const axios = require('axios')
const router = express.Router()

router.post('/', (req, res) => {
  console.log(req.body.myFormData) //giving undefined //tried req.myFormData too
  console.log(JSON.parse(req.body.myFormData.userName))
  axios({
    method: 'post',
    url: '/sendMyFilesEndpointUrl',
    data: req.body.myFormData,
    headers: {
      apiKey: 'keytoapi',
      'Content-Type': 'multipart/form-data'
    }
  })
    .then(response => {
      
      return res.send(res)
    })
    .catch(error => {
      console.error('error')
     }

22 thoughts on “How to send form data from React to the Node JS back end server”

  1. 593698 949620If running proves to be a dilemma then it might be wise to locate alternative exercises such as circuit training, weight training, swimming or cycling. 818010

    Reply

Leave a Comment