简体   繁体   English

Node JS,React JS,使用 Fetch API 将图像作为表单数据发布 *500 错误*

[英]Node JS, React JS, using Fetch API to POST image as Form Data *500 error*

I am new to node js.我是节点 js 的新手。 I am trying to send an image uploaded by the user to be stored in my backend using express js, but I keep getting a 500 error.我正在尝试使用 express js 发送用户上传的图像以存储在我的后端,但我不断收到 500 错误。 What am I missing?我错过了什么?

This is my front end code:这是我的前端代码:

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));
    }

And this is the backend这是后端

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();
      }
  })
})

When you pass fetch a FormData object it will generate a suitable Content-Type header automatically.当您通过fetch FormData object 时,它将自动生成合适的 Content-Type header。

You are overriding that with 'multipart/form-data' which is missing the mandatory boundry attribute.您正在使用缺少强制boundry属性'multipart/form-data'覆盖它。 Don't do that .不要那样做

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM