【问题标题】:Node JS, React JS, using Fetch API to POST image as Form Data *500 error*Node JS,React JS,使用 Fetch API 将图像作为表单数据发布 *500 错误*
【发布时间】:2020-09-07 09:18:30
【问题描述】:

我是节点 js 的新手。我正在尝试使用 express js 发送用户上传的图像以存储在我的后端,但我不断收到 500 错误。我错过了什么?

这是我的前端代码:

const formData = new FormData();
        formData.append("myImage",this.state.fotoSelected);
        fetch("http://localhost:9000/producto", {
            method: 'post',
            body: formData,
            headers: {
                'Content-Type': 'multipart/form-data'
            },
        })
            .then(response => {
                return response
            })
            .catch(error => console.error('Error:', error))
            .then(response => console.log('Success:', response));
    }

这是后端

const multer = require('multer');
const upload = multer({
  limits:{fileSize: 1000000},
}).single("myImage");

router.post('/', function (req, res) {
  upload(req, res, function (err) {
      iconsole.log("Request ---", req.body);
      console.log("Request file ---", req.file)
      if(!err) {
          return res.send(200).end();
      }
  })
})

【问题讨论】:

  • iconsole.log("Request ---", req.body); i 的错字?
  • 我认为@Phix 提到的内容引发了 500 错误

标签: javascript node.js reactjs express fetch-api


【解决方案1】:

当您将fetch 传递给FormData 对象时,它将自动生成合适的Content-Type 标头。

您将使用缺少 ma​​ndatory boundry 属性的 'multipart/form-data' 覆盖它。 不要这样做

【讨论】:

    猜你喜欢
    • 2018-12-11
    • 2019-05-30
    • 2019-01-29
    • 1970-01-01
    • 1970-01-01
    • 2013-01-17
    • 1970-01-01
    • 2019-11-30
    相关资源
    最近更新 更多