【问题标题】:Cannot read property 'path' of undefined while uploading image upload on the frontend(react)在前端上传图片上传时无法读取未定义的属性“路径”(反应)
【发布时间】:2021-04-01 00:27:19
【问题描述】:

我正在尝试在前端上传图片,但这不起作用,我收到以下错误

message: "Cannot read property 'path' of undefined"
status: "fail"

当我在后端记录 req.file 并尝试在前端上传时,我在控制台中得到未定义,但这会为 req.body 记录

[Object: null prototype] {
  name: 'sfdgg',
  description: 'dsfdgg',
  reviewImage: '[object Object]' }

图片上传在后端通过 Postman 可以正常工作。

这是前端逻辑

const formData = new FormData();

for (let key in review) {
  formData.append(key, review[key]);
}

formData.append("reviewImage", reviewImage)

console.log(reviewImage)

axios.post("http://localhost:3001/api/v1/reviews", formData,{
    headers: {
        "content-type": "multipart/formdata"
    }
})

删除内容类型不起作用,因为它也不适用于内容类型。

Multer 配置

const upload = multer({
  storage: storage,
  limits: {
    fileSize: 1024 * 1024 * 5,
  },
  fileFilter: fileFilter,
});

upload.single("reviewImage");

看到类似的问题,但答案对我不起作用,请协助。

【问题讨论】:

  • 错误实际发生在哪里?
  • 该问题可能是由于request参数中的reviewImage对象缺少key路径。
  • 前端出现错误@Jayce444

标签: javascript node.js reactjs express multer


【解决方案1】:

试试这个在表单数据中添加文件

var formData = new FormData();
var imagefile = document.querySelector('#reviewImage');
formData.append("reviewImage", imagefile.files[0]);
axios.post("http://localhost:3001/api/v1/reviews", formData, {
    headers: {
        "content-type": "multipart/formdata"
    }
})

【讨论】:

    猜你喜欢
    • 2021-11-03
    • 1970-01-01
    • 2021-07-11
    • 2020-02-08
    • 1970-01-01
    • 2017-09-23
    • 1970-01-01
    • 1970-01-01
    • 2019-06-12
    相关资源
    最近更新 更多