POST请求http://localhost:3000/programare返回404,预约数据无法存入MongoDB
问题原因&修复方案
1. 请求地址端口错误
你后端服务在server.js中配置的监听端口是5000,但前端axios请求写的是3000端口,3000是React开发服务的默认端口,根本没有处理对应POST请求的逻辑,所以返回404。
2. 路由前缀不匹配
你在server.js中用app.use('/user', require('./routes/userRouter'))挂载了用户路由,这意味着该路由下所有接口的路径都会自动带上/user前缀,你写的/programare接口实际可访问路径是http://localhost:5000/user/programare,不是你前端请求的根路径下的/programare。
3. 模型导出错误
你把预约模型和用户模型写在同一个文件中,连续两次使用module.exports,后者会覆盖前者的导出,导致路由中导入的Prog模型不存在,后续保存逻辑会报错。
4. 路由逻辑不完善
当前路由的POST处理逻辑没有返回响应,也没有异常捕获,请求即便走到路由也会超时。
具体修改步骤
- 修改前端请求地址
找到booking.js中的axios请求代码,替换为:
axios.post("http://localhost:5000/user/programare", newProgramare) .then(res => console.log("预约提交成功", res)) .catch(err => console.error("提交失败", err))
- 拆分模型文件
- 新建
models/Programare.js,仅存放预约相关的schema和模型:
const mongoose = require("mongoose"); const programareSchema = { date: String, email: String, firstName: String, hour: String, lastName: String, phoneNumber: String, }; module.exports = mongoose.model("Programare", programareSchema)
- 原来的模型文件仅保留用户相关代码,作为
models/User.js。
- 修正路由代码
在userRouter.js顶部先导入预约模型,再完善接口逻辑:
const express = require('express') const router = express.Router() const Prog = require('../models/Programare') // 导入预约模型 router.route("/programare").post(async (req,res)=>{ try { const {firstName, lastName, phoneNumber, email, date, hour} = req.body; const newProgramare = new Prog({ firstName, lastName, phoneNumber, email, date, hour }) await newProgramare.save(); return res.status(201).json({success: true, msg: "预约保存成功"}) } catch (err) { return res.status(500).json({success: false, msg: err.message}) } }) module.exports = router;
- 启动验证
先启动后端服务确认端口5000正常监听,再启动前端项目,提交表单即可正常存入MongoDB。
内容的提问来源于stack exchange,提问作者viorel Grigoras
相关产品推荐
相关产品推荐

