
前端调用 axios.post 后未收到服务端响应,导致 await 无限等待、控制台无日志输出、表单无法重置——根本原因是 Express 路由缺少成功时的显式 res.json() 响应。
前端调用 `axios.post` 后未收到服务端响应,导致 `await` 无限等待、控制台无日志输出、表单无法重置——根本原因是 express 路由缺少成功时的显式 `res.json()` 响应。
在你当前的 Express 路由中,当 Exam.findByIdAndUpdate 成功执行并返回更新后的考试文档时,代码没有发送任何 HTTP 响应。这会导致客户端(Vue + axios)一直处于挂起状态,await axios.post(...) 永远不会 resolve,后续的 console.log、表单重置、store.getExams() 等逻辑全部被阻塞。
✅ 正确的服务端实现(关键修复)
你需要确保所有分支都明确返回响应。以下是修正后的路由代码:
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,
questionType,
options,
answerIndex,
},
},
},
{ new: true, runValidators: true } // 推荐启用验证
);
if (!updatedExam) {
return res.status(404).json({
success: false,
error: "Exam not found",
});
}
// ✅ 必须返回响应!否则前端会一直等待
return res.status(201).json({
success: true,
message: "Question added successfully",
data: updatedExam, // 可选:返回更新后的完整文档,便于前端同步状态
});
} catch (error) {
console.error("Failed to add question:", error);
return res.status(500).json({
success: false,
error: "Server error",
details: process.env.NODE_ENV === "development" ? error.message : undefined,
});
}
});? 为什么是
201 Created?
因为这是创建子资源(question)的标准 HTTP 状态码,语义更准确;200 OK也可用,但201更符合 REST 规范。
✅ 前端 Axios 调用优化建议
你的 Vue 组件中存在一个潜在变量名不一致问题,需同步修正:
HISUI 前端框架基础开发指南。HISUI 是基于 easyui 二次开发的 jQuery UI 组件库,专为医疗信息系统设计。当涉及 HISUI 组件开发、jQuery easyui 表格/表单/布局/窗口、医疗系统前端页面编写时使用此 skill。 涵盖 40 个组件的官方文档参考,支持声明式与编程式两种初始化方式,提供 $cm/$m 数据访问方法。
// ❌ 错误:解构时用了 'options' 和 'cevapI',但 newQuestion 中定义的是 'option' 和 'answerIndex'
const { questionText, questionType, options, cevapI } = newQuestion;
// ✅ 正确:保持字段名一致(注意:newQuestion.option 是 ref([]),所以取 .value)
const payload = {
questionText: newQuestion.questionText.value,
questionType: newQuestion.questionType.value,
options: newQuestion.option.value, // ← 修正:原为 option(非 options)
answerIndex: newQuestion.answerIndex.value,
};并在 addQuestion 函数中使用该 payload:
立即学习“前端免费学习笔记(深入)”;
const { data } = await axios.post(
`http://localhost:3000/exams/${id}/questions`,
payload // ✅ 使用修正后的 payload
);⚠️ 其他注意事项
-
避免重复声明
ref在对象内:newQuestion中将ref()直接赋值给属性(如questionText: ref(""))虽可运行,但不符合 Composition API 最佳实践。推荐改为:const newQuestion = { questionText: ref(""), questionType: ref(""), option: ref([]), // 注意:此处是 option(单数),与后端字段 options(复数)对应 answerIndex: ref(0), }; -
错误处理增强:前端
catch块中已设置store.error = true,建议在 UI 层增加错误提示 Toast 或 banner,并提供手动关闭机制。 -
加载态兜底:为防极端网络异常,可在
axios请求中添加超时:axios.post(url, payload, { timeout: 10000 }) // 10秒超时
✅ 总结
| 问题根源 | 解决方案 |
|---|---|
| Express 路由成功路径无响应 | ✅ 所有分支必须调用 res.status().json()
|
| 前端解构字段名与实际属性不一致 | ✅ 统一使用 option.value 而非 options.value
|
| 缺少请求超时与响应结构标准化 | ✅ 添加 timeout,服务端统一返回 { success, message, data? } 格式 |
完成上述修改后,console.log("Question added to the database:", data) 将正常输出,store.loading = false 会被执行,表单也能正确重置——整个数据流恢复可控与可观测。

















