我正在尝试允许用户编辑他们的个人资料,我目前正在使用以下内容,但这不起作用。
我喜欢的表格
<form action="/dashboard/users/edit/:id" method="put">
我有我的路线
// users put
router.put('/dashboard/users/edit/:id', (req, res) => {
const user = {
schoolName: req.body.schoolName,
schoolAddress: req.body.schoolAddress,
schoolAddress2: req.body.schoolAddress2,
city: req.body.city,
zipCode: req.body.zipCode,
postalAddress: req.body.postalAddress,
postalCity: req.body.postalCity,
postalZipCode: req.body.postalZipCode,
telephone: req.body.telephone,
email: req.body.email,
password: req.body.password,
schoolType: req.body.schoolType,
schoolDistrict: req.body.schoolDistrict,
schoolRegion: req.body.schoolRegion,
curriculum: req.body.curriculum,
directorName: req.body.directorName,
directorTelephone: req.body.directorTelephone,
directorEmail: req.body.directorEmail,
schoolRepresentativeName: req.body.schoolRepresentativeName,
schoolRepresentativeTelephone: req.body.schoolRepresentativeTelephone,
schoolRepresentativeEmail: req.body.schoolRepresentativeEmail,
schoolRepresentativePosition: req.body.schoolRepresentativePosition,
schoolRepresentativeTShirt: req.body.schoolRepresentativeTShirt,
schoolRepresentativeTutorMentor: req.body.schoolRepresentativeTutorMentor
};
User.findByIdAndUpdate(req.params.id, user, function(err, raw){
if(err) {
res.send(err);
}
res.send(raw);
});
});
我无法看到让数据库更新。
此处的任何帮助表示赞赏。
答案 0 :(得分:0)
HTML表单不支持PUT方法。正如here所解释的那样,表单将作为GET请求发送。这可能是因为您在发送GET请求时期望PUT方法永远不会执行路由器处理程序的原因。
为了解决这个问题,您可以将路由器处理程序和表单方法都设置为POST。
我不确定您是否拥有完全相同的表单代码,或者您为了简单起见将“:id”作为action属性的一部分,但以防万一我将做出以下注释。
要记住的一点是,表单属性操作中的“:id”不是您尝试编辑的用户的实际ID。它将始终命中/ dashboard / users / edit /:id而不是/ dashboard / users / edit / 4832(假设4832是真实的userId)。
您需要在表单操作中获得实际ID。
例如:
<form action="/dashboard/users/edit/4832" method="post">
。这样当Express读取req.params.id时,它可以检索有效的id,如4832而不是“:id”