我正在尝试将表单数据发送到我的nodejs后端,但是我的后端打印出一个空对象。
我想使用formdata发送文本和图片
这是我代码的前端部分
const formdata = new FormData();
formdata.append("firstname", firstname);
formdata.append('lastname', lastname);
formdata.append('phone', phoneNumber);
formdata.append('address', address);
formdata.append('town', town);
formdata.append('city', city);
formdata.append('itLevel', itLevel);
formdata.append('smartphone', smartphone);
formdata.append('mapleOffers', mapleOffers);
formdata.append('mapleColors', mapleColors);
formdata.append('reason', reason);
formdata.append("file", photoID.image, photoID.image.name.replace(/\s/g, ""));
await Axios.post('/api/apply', formdata, {
headers: {
'Content-Type': 'application/json'
}
});
这是我的后端(nodejs)
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const uploadFiles = require('./Utils/uploadFile');
var multer = require('multer')
// var upload = multer({ dest: 'uploads/' })
var upload = multer()
const PORT = process.env.PORT || 3005;
app.use(bodyParser.json({limit: '50mb'}))
app.use(bodyParser.urlencoded({ extended: true, limit:'50mb' }))
app.use(upload.array('file'));
app.use(express.static('client/build'));
app.post('/api/apply', uploadFiles('file'), async(req, res) => {
try {
const uploadeFiles = req.uploadeFiles
console.log(uploadeFiles)
console.log(req.body); //returns {}
res.send('ok')
} catch (error) {
console.log(error.message)
}
})
app.listen(PORT);
有帮助吗?
答案 0 :(得分:1)
const formdata = new FormData();
让我们从图片开始
formdata.append('image', imageFile);
用于文本
formdata.append('userName', 'Fred');
然后请求axios
axios({
method: 'post',
url: 'yoururl', //addyoururl
data: formdata,
headers: {'Content-Type': 'multipart/form-data' }
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});