向数据库添加问题成功但无日志输出,页面加载停滞且表单无法重置
问题排查:Vue3 + Express 新增试题后前端无响应问题
核心问题分析
数据库已成功新增试题,但前端无日志输出、页面持续加载、表单无法重置,根源在于后端未返回响应,同时前端存在变量解构错误与状态清理遗漏。
后端代码修复
Express路由中,成功更新数据库后未向客户端返回响应,导致前端Axios请求一直处于pending状态,无法进入后续逻辑:
router.post("/:id/questions", async (req, res) => { const { id } = req.params; const { questionText, questionType, options, answerIndex } = req.body; try { const updatedExam = await Exam.findByIdAndUpdate( id, { $push: { questions: { questionText: questionText, options: options, questionType: questionType, answerIndex: answerIndex, }, }, }, { new: true } ); if (!updatedExam) { return res.status(404).json({ error: "Exam not found" }); } // 新增:返回更新后的考试数据或成功提示 res.status(200).json({ message: "Question added successfully", data: updatedExam }); } catch (error) { res.status(500).json({ error: "Server error" }); console.log(error); } });
前端代码修复
- 变量解构错误:newQuestion中定义的是
option,但解构时写成了options,同时误用了不存在的cevapI,应改为answerIndex:
// 原错误代码 const { questionText, questionType, options, cevapI } = newQuestion; // 修复后 const { questionText, questionType, option: options, answerIndex } = newQuestion;
- 状态清理遗漏:请求成功后未将
store.loading设为false,同时需完整重置表单所有字段:
const addQuestion = async () => { try { store.loading = true; const examToUpdate = exams.find((exam) => exam.examName === selectedExam); const { questionText, questionType, option: options, answerIndex } = newQuestion; if (!examToUpdate) { throw new Error('Exam not found'); } const id = examToUpdate._id; const { data } = await axios.post( `http://localhost:3000/exams/${id}/questions`, { questionText: questionText.value, questionType: questionType.value, options: options.value, answerIndex: answerIndex.value, } ); console.log("Question added to the database:", data); // 完整重置表单所有字段 newQuestion.questionText.value = ""; newQuestion.questionType.value = ""; newQuestion.option.value = []; newQuestion.answerIndex.value = 0; await store.getExams(); // 请求成功后关闭loading store.loading = false; } catch (error) { store.loading = false; store.error = true; store.errorMesssage = error.message; } };
- 响应式对象优化(可选):将newQuestion改为单个ref包裹的对象,更符合Vue3响应式最佳实践:
// 原写法 let newQuestion = { questionText: ref(""), questionType: ref(""), option: ref([]), answerIndex: ref(0) }; // 优化后 const newQuestion = ref({ questionText: "", questionType: "", option: [], answerIndex: 0 }); // 使用时直接访问newQuestion.value.questionText即可,无需.value嵌套
总结
- 后端必须在请求处理完成后返回响应,避免前端请求挂起;
- 前端需确保变量解构与定义一致,同时在请求完成(成功/失败)后统一管理loading状态;
- 响应式数据结构尽量简洁,减少嵌套ref的使用。
内容的提问来源于stack exchange,提问作者Emir
相关产品推荐
相关产品推荐

