我尝试更新 Mern Stack 应用程序中的数据,但发现表单数据为空,我想知道为什么!
我获取了所有值并将它们传递到函数 update 中以更新数据,然后将它们放入表单数据中,我发现表单数据为空。
客户端:
// file is empty not selected from the input
const UpdateModule = async (annee, name, file, desc, id) => {
const data = new FormData();
data.append('annee', annee);
data.append('name', name);
data.append('desc', desc);
if (file) {
data.append('file', file);
}
console.log('FormData:', data); // here is empty
// all the log below are not empty!
console.log('annee:', annee);
console.log('name:', name);
console.log('desc:', desc);
console.log('file:', file);
const config = {
headers: {
'content-type': 'multipart/form-data',
'accept': 'application/json'
}
};
await axios.patch('http://localhost:5000/api/module/'+id,data,config).then(res => {
// console.log(data)
setLoadingUpdate(false)
// setRefrech(refrech => refrech + 1)
setSuccessUpdate(true)
setErrorUpdate(false)
}).catch(error => {
console.log(error.message)
console.log(error.response.data)
setErrorUpdate(error.response.data)
setSuccessUpdate(false)
setLoadingUpdate(false)
})
}
服务器端:
const EditModule = async (req, res) => {
try {
const { id } = req.params
const data = req.body
const module = await Modules.findById(id)
consol.log(data)
console.log(module)
if (!module) {
return res.status(400).send('module not found')
}
const moduleUpdated = await Modules.findByIdAndUpdate(id, data, { new: true })
console.log(moduleUpdated)
res.status(201).json(moduleUpdated)
} catch (error) {
console.log(error.message)
}
}
事实上,你的
formData
就在那里。你不能那样记录它。请尝试这个:
for (var [key, value] of data.entries()) {
console.log(key, value);
}
看起来您正在使用express,这意味着您应该为请求正文指定适当的
body-parser
中间件以包含正文。
在定义路由之前添加主体解析器中间件
app.use(express.urlencoded());