Shiv Shankar Prasad
Shiv Shankar Prasad

Reputation: 157

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

I am trying to send the form data to the node server, the data is showing at the time of request in the network payload but not reaching to the node server. Request initiator file.

let formData = new FormData();

         // formData.append('test', 'hello');
         formData.append('productImage', productImage);
         // console.log(productName);
         formData.append('productName', productName);
         formData.append('productDesc', productDesc);
         formData.append('productPrice', productPrice);
         formData.append('productCategory', productCategory);
         formData.append('productQty', productQty);
         // var options = { content: formData };

         console.log(formData.entries());

         createProduct(formData)
            .then((response) => {
               console.log('server response = ', response);
            })
            .catch((err) => {
               console.log('Error Occurred ', err);
            });
      }

product.js file

import axios from 'axios';

export const createProduct = async (formData) => {
   console.log(formData);
   const response = await axios.post('/api/products/', formData);

   return response;
};

server.js file

const express = require('express');
const app = express();
const cors = require('cors');
const morgan = require('morgan');
const cookieParser = require('cookie-parser');
const connectDB = require('./database/db');

const authRoutes = require('./routes/auth');
const categoryRoutes = require('./routes/category');
const productRoutes = require('./routes/products');

app.use(cors());
app.use(morgan('dev'));
app.use(express.json());
app.use(cookieParser());
// app.use(express.json());

app.use('/api/auth', authRoutes);
app.use('/api/category', categoryRoutes);
app.use('/api/products', productRoutes);

connectDB();

const port = process.env.PORT || 5000;

app.listen(port, () => console.log(`listening to port ${port}`));

routes/products.js

const express = require('express');
const router = express.Router();
const productsController = require('../controllers/products');
const { authenticateJWT } = require('../middleware/authenticator');

router.post('/', authenticateJWT, productsController.create);
// router.get('/', authenticateJWT, categoryController.readAll);

module.exports = router;

controllers/products.js

const Products = require('../models/Products');

exports.create = async (req, res) => {
   // const { product } = req.file;

   console.log(req.body);

   try {
      // const categoryExists = await Category.findOne({ category });
      // let newProduct = new Products();
      //   newProduct.product_name = ;
      // newProduct = await newProduct.save();
      res.status(200).json({
         successMessage: '  was created',
      });
   } catch (err) {
      console.log('Category create error', err);
      return res.status(500).json({
         errorMessage: 'Please try again later',
      });
   }
};

It shows the empty object in the console while printing the req.body.

GET /api/category/ 304 2935.667 ms - -
[0] {}
[0] POST /api/products/ 200 4.827 ms - 34

enter image description here

see the network payload shows the data.

can anyone help me??

Upvotes: 2

Views: 3314

Answers (2)

mirsahib
mirsahib

Reputation: 445

Try changing
headers: { 'Content-Type': 'multipart/form-data' }
To
headers: { 'Content-Type': 'application/json' }
and add the following line

app.use(bodyParser.urlencoded({ extended: true })); //this line is already mentioned above
app.use(bodyParser.json());//add this line

Upvotes: 1

michael
michael

Reputation: 4173

Try to add content type to headers on axios.post.

export const createProduct = (formData) => {
  return axios({
    method: 'post',
    url: '/api/products/',
    data: formData,
    headers: { 'Content-Type': 'multipart/form-data' }
  });
};

Also use bodyParser.urlencoded() middleware on server side.

const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));

You will get data from req.body.

Upvotes: 1

Related Questions