通过使用 formData 获取文件将文件发送到 Nodejs 服务器 returns req.files null

sending file via fetch with formData to Nodejs server returns req.files null

我总是通过将操作属性和多部分 enctypes 与我的 html 表单一起发送文件和表单数据。最近我需要使用 fetch 来发送一个表单并使用 new FormData() 可以读取给定 html 表单的所有字段和文件。但是在nodejs端,req.filesreturnsnull。当我使用表单 action 属性时,它工作得很好。

客户端

let formData = new FormData(document.getElementById('additem'));
let response = await fetch(`${window.location.href}/inventory`, {
            method: "POST",
            body: formData
        });

在服务器端,我只使用 express-bodyparser(现在是默认设置)并尝试使用 req.files 访问文件; 我知道我可以使用 multerformidable 但我想知道是否有办法让它与我的 atm 一起使用。 谢谢。

如果您要发送需要指定的文件,您的 Content-Type 在哪里 在它们 headers 上,默认情况下 content-type 是 application/json

Mozilla 文档中有很好的示例:https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

On the server end I am just using express-bodyparser (which is default now) and am trying to access the files with req.files; I know I can use multer or formidable but I was wondering if there's a way to make it work with what I have atm.

不,没有。 FormData 个对象生成多部分主体。

the documentation for body parser

This does not handle multipart bodies, due to their complex and typically large nature. For multipart bodies, you may be interested in the following modules:

  • busboy and connect-busboy
  • multiparty and connect-multiparty
  • formidable
  • multer