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

Fre*_*e09 7 html javascript node.js express reactjs

我想将文件发送到我的 Express 应用程序作为后端。我的问题是我的正文是作为类型发送的application/json,我想将其作为 a 发送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));
Run Code Online (Sandbox Code Playgroud)

当我想登录req.fileapi 断点时,我得到了undefined.

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

我使用钩子存储表单中的反应数据,该对象如下所示:

{
   name: 'test',
   surname: 'test2',
   cv: 'C:\\fakepath\\Babel error.png'
}
Run Code Online (Sandbox Code Playgroud)

Bri*_*ius 8

您需要使用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
});
Run Code Online (Sandbox Code Playgroud)