使用React Axios nodejs使用Multer上传图像,但formdata具有嵌套对象的嵌套数组
我正在尝试做两件事。使用嵌套对象(iNCredientSlist)将我的表单数据保存在我的后端,并用Axios帖子上传两个图像('Cuisineimg'和'imgurl')。请参阅下面的设置:
const Create = (props) => {
const units = ["none", "block(s)", "bushel(s)", "clove(s)", "can(s)",
"drop(s)", "smidgen", "pinch", "dash", "teaspoon(s)", "tablespoon(s)",
"fl oz(s)", "ounce(s)", "cup(s)", "pint(s)", "quart(s)", "gallon(s)",
"pound(s)", "milliliter(s)", "liter(s)"]
const [form, setForm] = useState({
title: "",
description: "",
ingredientsList: [
{ ingredient: "", quantity: 0, unit: units[0] },
],
cuisineImg: "",
imgUrl: "",
const onSubmitHandler = (event) => {
event.preventDefault();
const formData = new FormData();
for (let formKey in form) {
if (typeof (form[formKey]) === 'object') {
for (let objectKey in form[formKey]) {
formData.append(`${formKey}.${objectKey}`, JSON.stringify(form[formKey][objectKey]));
}
}
else {
formData.append(i, form[i])
}
}
const config = {
headers: {
'Content-Type': 'multipart/form-data'
},
}
axios.post("http://localhost:8000/api/recipes/create", formData, config)
.then(res => {
console.log(res);
history.push("/")
})
.catch(err => {
setErrors(err.response.data.err.errors)
});
}
有两件事错误。第一,我的信息在我的后端像这样回到了[对象:null Prototype],然后是我的数据。
req body: [Object: null prototype] {
title: 'Test',
description: 'blah',
'ingredientsList.0': '{"ingredient":"tofu","quantity":"1","unit":"block(s)"}',
'ingredientsList.1': '{"ingredient":"onion","quantity":"2","unit":"block(s)"}',
'imgUrl.name': '"Screen Shot 2022-04-03 at 9.19.46 AM.png"',
'imgUrl.lastModified': '1648991991606',
'imgUrl.lastModifiedDate': '"2022-04-03T13:19:51.606Z"',
'imgUrl.webkitRelativePath': '""',
'imgUrl.size': '85483',
'imgUrl.type': '"image/png"',
'imgUrl.arrayBuffer': 'undefined',
'imgUrl.slice': 'undefined',
'imgUrl.stream': 'undefined',
'imgUrl.text': 'undefined',
}
第二,图像和成分列表随着数字迭代而返回。我希望将数据像在模式中一样,用一个称为“ IngredientsList”的嵌套对象,带有嵌套对象值和“ Cuisineimg”是一个具有文件路径值的密钥,等等。相反,随着迭代多次,他们回来了。
这是我的路由设置:
Route.js
const multer = require('multer');
// other code removed for clarity
const upload = multer({storage: storage})
module.exports = app => {
app.post("/api/recipes/create", upload.fields([{ name: 'cuisineImg', maxCount: 1 }, { name: 'imgUrl', maxCount: 1 }]), RecipeController.createRecipe);}
Controller.js
module.exports.createRecipe = (req, res) => {
req.body.rating = 0;
Recipe.create((req.body))
.then(newRecipes => {
res.json({ results: newRecipes });
})
.catch(err => res.status(400).json({ message: "that didn't work", err }))
}
前端错误消息: 我的前端错误表明InfredientsList具有铸件错误,我可以从Req.body中的信息中看到这一点。这是我在控制台消息上看到的错误:
“配方验证失败:infredientsList:cast to嵌入到嵌入式失败的值“ {” iNgreDient':“ tofu”,“ dentity”:“ 1”:“ 1”,“单位”:“ block(s)” “}”(键入字符串)在路径“ intredientsList”上,因为“ objectParameTerErr”,
后端: 我尝试了json.parse(req.body),但我得到了“ TypeError:无法将对象转换为原始值”。
我对所有这些活动部件都迷失了方向。有什么想法吗?
I'm trying to do two things. Save my form data in my backend with nested objects (ingredientsList) and upload two images ('cuisineImg' and 'imgUrl') with an axios post. See below setup:
const Create = (props) => {
const units = ["none", "block(s)", "bushel(s)", "clove(s)", "can(s)",
"drop(s)", "smidgen", "pinch", "dash", "teaspoon(s)", "tablespoon(s)",
"fl oz(s)", "ounce(s)", "cup(s)", "pint(s)", "quart(s)", "gallon(s)",
"pound(s)", "milliliter(s)", "liter(s)"]
const [form, setForm] = useState({
title: "",
description: "",
ingredientsList: [
{ ingredient: "", quantity: 0, unit: units[0] },
],
cuisineImg: "",
imgUrl: "",
const onSubmitHandler = (event) => {
event.preventDefault();
const formData = new FormData();
for (let formKey in form) {
if (typeof (form[formKey]) === 'object') {
for (let objectKey in form[formKey]) {
formData.append(`${formKey}.${objectKey}`, JSON.stringify(form[formKey][objectKey]));
}
}
else {
formData.append(i, form[i])
}
}
const config = {
headers: {
'Content-Type': 'multipart/form-data'
},
}
axios.post("http://localhost:8000/api/recipes/create", formData, config)
.then(res => {
console.log(res);
history.push("/")
})
.catch(err => {
setErrors(err.response.data.err.errors)
});
}
There are two things wrong. One, my info is coming back like this on my backend where the req.body in [Object: null prototype], then my data.
req body: [Object: null prototype] {
title: 'Test',
description: 'blah',
'ingredientsList.0': '{"ingredient":"tofu","quantity":"1","unit":"block(s)"}',
'ingredientsList.1': '{"ingredient":"onion","quantity":"2","unit":"block(s)"}',
'imgUrl.name': '"Screen Shot 2022-04-03 at 9.19.46 AM.png"',
'imgUrl.lastModified': '1648991991606',
'imgUrl.lastModifiedDate': '"2022-04-03T13:19:51.606Z"',
'imgUrl.webkitRelativePath': '""',
'imgUrl.size': '85483',
'imgUrl.type': '"image/png"',
'imgUrl.arrayBuffer': 'undefined',
'imgUrl.slice': 'undefined',
'imgUrl.stream': 'undefined',
'imgUrl.text': 'undefined',
}
Two, the images and the ingredientsList come back as iterated with numbers. I want the data to be parsed like how I have in my schema, with nested objects in one key called 'ingredientsList' with a nested object value and 'cuisineImg' is one key with a file path value, and so forth. Instead they are coming back as iterated multiple times.
And here is my route setup:
route.js
const multer = require('multer');
// other code removed for clarity
const upload = multer({storage: storage})
module.exports = app => {
app.post("/api/recipes/create", upload.fields([{ name: 'cuisineImg', maxCount: 1 }, { name: 'imgUrl', maxCount: 1 }]), RecipeController.createRecipe);}
controller.js
module.exports.createRecipe = (req, res) => {
req.body.rating = 0;
Recipe.create((req.body))
.then(newRecipes => {
res.json({ results: newRecipes });
})
.catch(err => res.status(400).json({ message: "that didn't work", err }))
}
Front-End Error Message:
My front-end error shows that ingredientsList has a cast error, which I can see from how the information is being received in req.body. This is the error I see on console message:
"Recipe validation failed: ingredientsList: Cast to embedded failed for value "{"ingredient":"tofu","quantity":"1","unit":"block(s)"}" (type string) at path "ingredientsList" because of "ObjectParameterError",
Backend:
I tried JSON.Parse(req.body) but i get "TypeError: Cannot convert object to primitive value."
I'm super lost with all these moving parts. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论