如何从 React js axios post 请求将 FormData 发送到节点服务器?

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


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);

            });

      }

产品.js 文件


import axios from 'axios';


export const createProduct = async (formData) => {

   console.log(formData);

   const response = await axios.post('/api/products/', formData);


   return response;

};


服务器.js 文件


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}`));



温温酱
浏览 80回答 2
2回答

MMTTMM

尝试更改headers: { 'Content-Type': 'multipart/form-data' }为headers: { 'Content-Type': 'application/json' }并添加以下行app.use(bodyParser.urlencoded({ extended: true })); //this line is already mentioned aboveapp.use(bodyParser.json());//add this line

交互式爱情

尝试将内容类型添加到 axios.post 上的标题中。export const createProduct = (formData) => {  return axios({    method: 'post',    url: '/api/products/',    data: formData,    headers: { 'Content-Type': 'multipart/form-data' }  });};还可以bodyParser.urlencoded()在服务器端使用中间件。const bodyParser = require('body-parser');app.use(bodyParser.urlencoded({ extended: true }));您将从 获取数据req.body。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript