我有下一个代码(前端):

let imagesData = new FormData();

button.addEventListener('click', () => {
const data = {
    id: 5,
    name: 'five'
}
uploadDataToServer(imagesData);
})
const uploadDataToServer = (data) => {
axios.post('http://localhost:5000/upload', data)
    .then((res) => console.log(res))
    .catch((err) => console.log(err));
}


下一个后端部分:

app.post('/upload', upload.array('fileLoader', 5), (req, res, next) => {
    const files = req.files;
    if (!files) {
        const error = new Error('Please upload a file');
        error.httpStatusCode = 400;
        return next(error);
    }
    res.send(files);
})


如何同时访问req.body中的对象数据和req.files中的图像?

最佳答案

您可以使用Formdata set-functionimagesData添加新值。



let imagesData = new FormData();

button.addEventListener('click', () => {

  /*
   * Attention the set-funcetion sets a new value for an existing key
   * or adds the key/value if it does not already exist
   */
  imagesData.set('id', 5);

  imagesData.set('name', 'five');

  uploadDataToServer(imagesData);

})
const uploadDataToServer = (data) => {
axios.post('http://localhost:5000/upload', data)
    .then((res) => console.log(res))
    .catch((err) => console.log(err));
}

09-25 19:36