如何从React js axios发布请求将FormData发送到节点服务器? [英] how do i send FormData to the node server from React js axios post request?

查看:31
本文介绍了如何从React js axios发布请求将FormData发送到节点服务器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将表单数据发送到节点服务器,该数据在请求时显示在网络有效负载中,但未到达节点服务器.请求启动器文件.

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文件

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文件

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

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

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',
      });
   }
};

它在打印 req.body 时在控制台中显示空对象.

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

查看网络有效负载显示的数据.

see the network payload shows the data.

有人可以帮我吗?

推荐答案

尝试更改
标题:{'Content-Type':'multipart/form-data'}

标头:{'Content-Type':'application/json'}
并添加以下行

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

这篇关于如何从React js axios发布请求将FormData发送到节点服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆