[英]How to pass array to formdata and save as array in react.js
我將一個數組傳遞給formdata,但將其作為字符串獲取。 我怎樣才能將它保存在數組中。
tags=["abc", "def", "ghi"]
formData.set("tags",tags);
如果我在前端這樣做,那么后端就不會保存任何東西
const clickSubmit = (event) => {
event.preventDefault();
setValues({ ...values, error: "", loading: true });
tags.forEach((tag) => formData.append("tags[]", tag));
createProduct(formData).then((data) => {
if (data.error) {
setValues({ ...values, error: data.error });
} else {
setValues({
...values,
name: "",
description: "",
});
}
});
};
提交表單后的后端代碼
exports.create = (req, res) => {
console.log("REQ", req.body);
let form = new formidable.IncomingForm();
form.keepExtensions = true;
form.parse(req, (err, fields, files) => {
if (err) {
return res.status(400).json({
error: "Image could not be uploaded",
});
}
let product = new Product(fields);
console.log("P", product);
if (files.photo) {
product.photo.data = fs.readFileSync(files.photo.path);
product.photo.contentType = files.photo.type;
}
product.save((err, result) => {
if (err) {
return res.status(400).json({
error: errorHandler(err),
});
}
res.json(result);
});
});
};
req.body 也給出了空的 object,為什么我要使用
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
這不是我們將數組傳遞給 formData 的方式。 您必須遍歷所有數組項並將它們一一添加到 formData 中。
const frmData = new FormData();
const tags = ["abc", "def", "ghi"];
tags.forEach(tag => frmData.append('tags[]', tag))
所以這里的要點是,當你想添加一個數組來形成數據時,你必須使用鍵名作為“key[]”,最后是數組符號。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.