如何在 React 中使用 fetch 和表单数据发布对象?

Posted

技术标签:

【中文标题】如何在 React 中使用 fetch 和表单数据发布对象?【英文标题】:How to post object using fetch with form-data in React? 【发布时间】:2019-12-26 23:19:26 【问题描述】:

我想将文件作为后端发送到我的快速应用程序。我的问题是我的正文以application/json 类型发送,我想将其作为form-data 发送,然后使用multer 上传此文件-> https://github.com/expressjs/multer

我不知道如何准备 fetch 调用以便稍后在 express 中获取它。

    fetch('/api/data', 
  method: 'POST',
  headers: 
    Accept: 'application/form-data',
    'Content-Type': 'application/json',
  ,
  body: JSON.stringify(data),
)
  .then((resp) => resp.json())
  .then((data) => console.log(data));

当我想在 api 断点中记录 req.file 时,我得到了 undefined

app.post('/api/data', upload.single('cv'), (req, res) => 
  console.log(req.body);
  console.log(req.file);
  res.send( name: 'Hello world!' );
);

我使用钩子从表单存储反应数据,这个对象看起来像这样:


   name: 'test',
   surname: 'test2',
   cv: 'C:\\fakepath\\Babel error.png'

【问题讨论】:

【参考方案1】:

您需要使用FormData API 构建您的请求正文。

FormData 接口提供了一种方法来轻松构造一组表示表单字段及其值的键/值对,然后可以使用 XMLHttpRequest.send() 方法轻松发送。如果编码类型设置为“multipart/form-data”,它使用与表单相同的格式。

const myFile = document.querySelector("input[type=file]").files[0];
const data = new FormData();
data.append("myFile", myFile);
data.append("otherStuff", "stuff from a text input");
fetch(target, 
    method: "POST",
    body: data
);

【讨论】:

req.file 仍然发送未定义 啊,是的,我忘记了文件输入类型的行为有点不同。您必须参考 Element.files[0]。我更正了我的示例,使其可以正常工作。 我的荣幸 :o)

以上是关于如何在 React 中使用 fetch 和表单数据发布对象?的主要内容,如果未能解决你的问题,请参考以下文章