为什么我的文件数组没有附加到FormData?

问题描述 投票:0回答:1

我被困在这三天了。我在这个网站上尝试了几乎所有的解决方案,我甚至在其他网站上寻求帮助。

我正在尝试发送一个FormData对象作为正文的帖子请求。一切正常,除了我的图像数组以未定义/空的方式命中服务器这一事实,这导致文档被保存到数据库,其中空数组[]作为图像键的值。

在Postman上测试路线它完美地工作并保存我发送的图像阵列。所以我的前端代码有问题。是的,我的HTML文件输入的名称与后端的upload.array(名称,编号)相同。是的,Mongoose模型将键:值对设置为数组。是的,所有的multer都设置得很完美(单上传工作正常,并且在使用Postman测试时可以正常进行多次上传。)

据我所知,问题肯定在于下面的代码。好像我的文件数组没有附加到FormData。

// POST FUNCTIONALITY

//initializing Post Article variables
let formContent = "";
let fileInput = [];

//listening for value changes in the Post Article form
function formDataChange() {
    document.getElementById("tArea").addEventListener("change", function(){
      formContent = document.getElementById("tArea").value;
    });
    document.querySelector("input[type='file']").addEventListener("change", function(){
      fileInput = Array.from(document.querySelector("input[type='file']").files);
      console.log(fileInput); //this console log outputs the array of files showing that the event listener at least is working properly
    });
};
formDataChange();

//listen for POST button
function listenPostArticle() {
  document.getElementById("postArticle").addEventListener("click", postArticle);
};
listenPostArticle();

//fire off POST request
function postArticle () {

let formdata = new FormData();

formdata.append("content", formContent);
formdata.append("jwt", token);

fileInput.forEach((f) => {
  formdata.append("image[]", f);
})


let req = new Request("http://localhost:8080/api/articles/", {method: 'POST', body: formdata,
headers:{'Authorization': "Bearer " + token}});

fetch(req)
  .then(res => res.json())
  .then((data) => {
    console.log(data);
    res.redirect("http://localhost:5500");
  })
}

猫鼬模式:

const mongoose = require("mongoose");

const ArticleSchema = new mongoose.Schema({
  _id: mongoose.Schema.Types.ObjectId,
  content: {type: String, required: true},
  image: {type: []},
  jwt: {type: String}
});

module.exports = Article = mongoose.model("article", ArticleSchema);

路线:

router.post("/", upload.array("image", 5), (req, res) => {
    const newArticle = new Article({
      _id: mongoose.Types.ObjectId(),
      content: req.body.content,
      image: req.files,
      jwt: req.body.jwt
    });
    newArticle
    .save()
    .then(result => {
      res.json({ message: "Article posted!"}); 
    })
});

Screenshot of Postman working successfully. Key field for images is "image"

javascript mongodb express mongoose multer
1个回答
0
投票

在您的标题中添加multipart / form-data

let req = new Request("http://localhost:8080/api/articles/", {method: 'POST', body: formdata,
headers:{'Authorization': "Bearer " + token,'Content-Type': 'multipart/form-data'}});
© www.soinside.com 2019 - 2024. All rights reserved.