在Express中如何POST至当前URL并重定向回原页面?
完善Express中Job编辑的POST路由实现
看起来你已经搭好了基本的编辑路由结构,我来帮你把postJob方法完善得更健壮,兼顾数据验证、错误处理和用户体验:
核心改进点拆解
- 先提取并验证表单提交的数据,避免无效数据进入数据库
- 处理数据库更新的成功/失败场景
- 合理的重定向和错误反馈,防止重复提交问题
完整实现代码
exports.postJob = async (req, res, next) => { try { // 1. 从请求中获取jobId和表单提交的数据 const { jobid } = req.params; const { title, description, salary, location } = req.body; // 替换成你表单里的实际字段 // 2. 数据验证:检查必填字段是否存在 if (!title || !description) { // 验证失败时,回到编辑页面并携带错误信息和用户已填数据 return res.render('jobs/edit', { job: { _id: jobid, title, description, salary, location }, errorMessage: '职位标题和描述为必填项' }); } // 3. 执行数据库更新操作(以Mongoose为例,可替换为你的数据库逻辑) const updatedJob = await Job.findByIdAndUpdate( jobid, { title, description, salary, location }, { new: true, runValidators: true } // new返回更新后文档;runValidators触发模型验证规则 ); // 4. 检查目标职位是否存在 if (!updatedJob) { const error = new Error('未找到该职位'); error.statusCode = 404; throw error; } // 5. 更新成功后重定向到职位详情页(避免刷新重复提交) res.redirect(`/jobs/${jobid}`); } catch (err) { // 6. 统一处理错误,传递给Express错误中间件 next(err); } };
额外提示
- 记得在编辑页面模板中渲染
errorMessage和回显用户已填数据,提升用户体验 - 如果用ORM(比如Mongoose),建议在Job模型里设置字段验证规则(如
title: { type: String, required: true }),配合runValidators: true实现数据库层面的二次校验 - 若不习惯async/await,可替换为Promise的
.then()/.catch()写法,逻辑保持一致
内容的提问来源于stack exchange,提问作者McB
相关产品推荐
相关产品推荐

