【问题标题】:Why is my array of files not appending to FormData?为什么我的文件数组没有附加到 FormData?
【发布时间】:2019-01-12 10:22:18
【问题描述】:

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

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

在 Postman 上测试路线,它运行良好并保存了我发送的图像数组。所以我的前端代码有问题。是的,我的 HTML 文件输入的名称与后端的 upload.array(name, number) 相同。是的,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");
  })
}

Mongoose 架构:

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"

【问题讨论】:

  • console.log(req);console.log(formdata)。确保它们设置正确。您也可以尝试使用MITM proxy 来检查正在设置的数据,以确保其设置正确。
  • 请也显示ajax代码
  • 你的意思是快递代码吗?我刚刚把我的 Mongoose+Express 代码放上去
  • 您能否从 Chrome(等)网络选项卡中发布 exactly 从客户端发送到服务器的内容?该帖子请求的内容是什么?

标签: javascript mongodb express mongoose multer


【解决方案1】:

在你的标题中添加 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'}});

【讨论】:

  • 你能发布你的后端代码吗?我的意思是您对数据的期望如何,发布请求时邮递员的屏幕截图也会有所帮助。
  • 添加了后端代码,将在几分钟内获取 Postman 屏幕截图。感谢您的帮助!
猜你喜欢
  • 2014-09-05
  • 1970-01-01
  • 2021-04-30
  • 2017-11-29
  • 1970-01-01
  • 1970-01-01
  • 2020-12-03
  • 2011-06-27
相关资源
最近更新 更多