使用React App中的axios将文件发送到服务器

时间:2020-05-28 01:43:15

标签: reactjs express 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);
});

1 个答案:

答案 0 :(得分:0)

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

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

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