我正在尝试将表单数据发送到节点服务器,数据在请求时显示在网络负载中,但未到达节点服务器。请求启动器文件。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}`));
2 回答
MMTTMM
TA贡献1869条经验 获得超4个赞
尝试更改
headers: { 'Content-Type': 'multipart/form-data' }
为
headers: { 'Content-Type': 'application/json' }
并添加以下行
app.use(bodyParser.urlencoded({ extended: true })); //this line is already mentioned above
app.use(bodyParser.json());//add this line
交互式爱情
TA贡献1712条经验 获得超3个赞
尝试将内容类型添加到 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。
添加回答
举报
0/150
提交
取消