首页 > 解决方案 > 在 react app 中使用 axios 向服务器发送文件

问题描述

我在 React 中使用 axios 来尝试将文件发送到服务器。有人可以告诉我我在这里做错了什么。没有错误。该form变量返回一个空对象。我完全被难住了。

小路:React submit call

handleSubmit(event) {
  event.preventDefault();
  this.props.uploadProducts(supplier_id, this.fileInput.current.files[0]);
}

小路:uploadProducts

export const uploadProducts = (supplier_id, file) => (dispatch, getState) => {
  const form = new FormData();

  form.append('my_field', 'my value');
  form.append('my_file', file);
  console.log(form);

  axios
    .post('http://localhost:3000/products', form, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
};

小路:Server

router.post('/products', async function (req, res, next) {
  console.log('res', req.body);
});

标签: reactjsexpressaxios

解决方案


FormData API 不会通过控制台直接记录它来返回您的值。它有一些辅助函数,其中一些是迭代器,以提取其值。查看更多:formData MDN

您的 axios 帖子似乎与您的路由器端点不匹配。axios 也是一个 Promise 库,因此您可以使用thenandcatch来处理解决和拒绝操作。

  axios
    .post('http://localhost:3000/upload/supplier/products', form, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    .then(res => console.log(res))
    .catch(err => console.log(err))

如果你定义你的函数,async你可以使用await并包装在一个 try catch 块中:

 try {
   const response = await axios
    .post('http://localhost:3000/upload/supplier/products', form, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
   console.log(response)
  } catch (e) {
    console.log(e) 
  }

推荐阅读