You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Axios & Express向MongoDB提交数据遇404错误,求路由排查

问题排查与修复

核心问题1:路由路径定义错误

Express 中定义路由时,第一个参数是相对服务器根目录的路径,而非完整的 URL。你的代码中用了 app.get('http://localhost:3001', ...) 和 app.post('http://localhost:3001', ...),这会让 Express 尝试匹配路径 http://localhost:3001/http://localhost:3001,显然不存在该路由,因此返回 404 错误。

核心问题2:POST 请求未完成数据库操作且未返回响应

原 POST 路由仅打印请求体,既没有将数据存入 MongoDB,也未给前端返回响应,会导致前端请求超时或无法确认操作结果。

额外问题:Schema 文件缺少 mongoose 引入

你的 item.js 中没有引入 mongoose,会直接抛出 mongoose is not defined 错误,导致数据库操作失败。


修复后的完整代码

server.js

const express = require('express')
const connectDB = require('./db.js')
const itemModel = require('./models/item.js')
const cors = require('cors')

const app = express()
app.use(express.json())
app.use(cors())
connectDB()

// 修正路由路径为相对路径 '/'
app.get('/', async (req, res) => {
    try {
        const response = await itemModel.find()
        return res.json({ workorders: response })
    } catch (err) {
        res.status(500).json({ error: err.message })
    }
})

// 修正路由路径,完善数据库保存逻辑并返回响应
app.post('/', async (req, res) => {
    try {
        const newWorkOrder = new itemModel(req.body)
        await newWorkOrder.save()
        res.status(201).json(newWorkOrder) // 返回创建成功的数据
    } catch (err) {
        res.status(400).json({ error: err.message })
    }
})

app.listen(3001, () => {
    console.log("app is running on port 3001");
}) 

item.js

// 新增 mongoose 引入
const mongoose = require('mongoose')

const itemSchema = new mongoose.Schema({
    customerName: String,
    jobDescription: String,
    jobPrice: String,
    laborNotes: String,
    laborType: String,
    IPWO: String,
    refWO: String,
    materialStatus: String,
    dateScheduled: Date,
    woStatus: String,
    notes: String
})

const itemModel = mongoose.model("workorders", itemSchema)
module.exports = itemModel

验证步骤

  1. 重启 Express 服务器
  2. 触发前端的 postData 函数,此时应该能成功将数据存入 MongoDB 的 test.workorders 集合
  3. 访问 http://localhost:3001 可以看到包含新数据的响应

内容的提问来源于stack exchange,提问作者Bkwiat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 04:06:22