【问题标题】:Trouble sending File from React frontend with Fetch to Express 4 API使用 Fetch 将文件从 React 前端发送到 Express 4 API 时遇到问题
【发布时间】:2019-08-14 09:37:27
【问题描述】:

我正在尝试将图像文件从我的 React 前端发送到我的 express API:

fetch('http://localhost:4000/upload/', {
  method: 'POST',
  body: this.state.picture[0],
})

当我记录它时,该文件在 chrome 控制台中看起来是正确的:

File {name: "31-614x614.jpg", lastModified: 1553111550472, lastModifiedDate: Wed Mar 20 2019 12:52:30 GMT-0700 (Pacific Daylight Time), webkitRelativePath: "", size: 95101, …}

但是,当我尝试在后端的请求中记录文件时,我会得到未定义或空的请求对象,具体取决于我的设置方式。

我已尝试使用 multer、busboy 和 express-fileupload,如类似堆栈溢出问题中的建议,但遇到了同样的问题。

这是我的路由器:

const Router = require('express').Router();
const imgController = require('./controllers/imgController');

Router.get('/images/', imgController.getImages);
Router.post('/upload/', imgController.postImage);

module.exports = Router;

以及我只是试图查看正在发送的文件的控制器:

exports.postImage = (req, res) => {
  console.log("IN POST IMAGE")
  console.log(req.body)
  console.log(req.files)
}

我确实进入了控制器,但请求从未包含该文件。 任何帮助表示赞赏!

【问题讨论】:

    标签: reactjs express fetch fetch-api


    【解决方案1】:

    您是否尝试过构建 formData 元素并发送它?

    var input = document.querySelector('input[type="file"]')
    
    var data = new FormData()
    data.append('file', input.files[0])
    data.append('user', 'hubot')
    
    fetch('/avatars', {
      method: 'POST',
      body: data
    })
    

    【讨论】:

    • 谢谢,刚刚试过,但没有骰子 :( 我相信这与我的服务器设置能够读取请求有关。
    • 您需要使用middleware 解析器来处理multipart/form-data 请求:github.com/expressjs/multer
    • 正如我的帖子中提到的,我尝试了上述两个包都无济于事。 express-fileupload 看起来也超级简单易用。
    • @David 然后用其中一个包向我们展示您的代码
    • 我使用您建议的表单数据和 multer 让它工作,问题是我需要让路由器使用正确的 Multer 中间件功能,而不是 express 应用程序。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2021-04-08
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    • 2020-10-29
    • 2018-07-06
    • 1970-01-01
    • 2022-01-28
    相关资源
    最近更新 更多