在 reactJS 中使用 "fetch" 上传文件

Uploading a file using "fetch" in reactJS

在 reactjs

中使用 "fetch" 上传文件

我正在尝试使用 ReactJS 上传文件。

handleUploadfile = (event) => {
        event.preventDefault();
        const data = new FormData();
        data.append('photo',event.target.files[0] );
        data.append('name', 'Test Name');
        data.append('desc', 'Test description');
        fetch("http://localhost:3001/todo/upload", {
             method: 'POST',
             headers: {
                 'Accept': 'application/json',
                 'Content-Type': 'application/x-www-form-urlencoded'
             },
             body: data
        }).then((response) =>  {
           return response.text();
        })
    }

出于某种原因,我无法使用以下方式读取 nodejs(+multer) 服务器上的文件:

req.files

在 post 路由器上显示 "undefined"。

终于找到解决方法

我不得不从 headers 部分删除 'Content-Type' 并且它在 nodejs 中使用 multer 解决了。

使用 "multipart/form-data"

'Content-Type': 'multipart/form-data'

要求我们设置边界,因此它在 nodejs 中抛出错误 "Error: Multipart: Boundary not found"

使用"application/x-www-form-urlencoded"

'Content-Type': 'application/x-www-form-urlencoded'

我得到 req.body 填充但作为字符串但无法访问单个值。

因此最终的解决方案是删除 'Content-Type'