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

开发支出追踪器后端提交请求时出现数据加载失败问题求助

问题排查与修复方案

核心问题分析

你的代码存在两个关键问题,直接导致请求失败和数据未入库:

  • 每次POST请求都重复发起MongoDB连接,mongoose不推荐这种方式,会引发连接冲突或资源耗尽
  • 异步操作未做错误处理,一旦连接或数据创建出错,服务器无法返回有效响应,前端就会出现“Failed to load response data”错误

修复后的完整代码

const express = require('express')
const app = express();
const cors = require('cors');
const Transaction = require('./models/Transaction.js')
const mongoose = require("mongoose");
require('dotenv').config();

// 中间件配置
app.use(cors());
app.use(express.json());

// 启动时只连接一次MongoDB
mongoose.connect(process.env.MONGO_URL)
  .then(() => console.log('MongoDB连接成功'))
  .catch(err => console.error('MongoDB连接失败:', err));

// 测试接口
app.get('/api/test', (req, res) => {
  res.json('test ok')
})

// 交易创建接口(添加错误处理)
app.post('/api/transaction', async (req, res) => {
  try {
    const { name, description, amount } = req.body;
    // 验证请求参数是否完整
    if (!name || !description || amount === undefined) {
      return res.status(400).json({ error: '缺少必要字段:name、description、amount均为必填项' });
    }
    const transaction = await Transaction.create({ name, description, amount });
    res.status(201).json(transaction);
  } catch (err) {
    console.error('创建交易失败:', err);
    res.status(500).json({ error: '服务器内部错误', details: err.message });
  }
})

app.listen(4000, () => {
  console.log('server is running on port 4000')
})

额外检查项

  • 确认.env文件放在项目根目录,且MONGO_URL变量格式正确(例如:mongodb+srv://<username>:<password>@cluster0.mongodb.net/<dbname>?retryWrites=true&w=majority)
  • 检查Transaction.js模型的schema定义,确保字段与请求参数匹配,示例如下:
// models/Transaction.js
const mongoose = require('mongoose');

const transactionSchema = new mongoose.Schema({
  name: { type: String, required: true },
  description: { type: String, required: true },
  amount: { type: Number, required: true }
});

module.exports = mongoose.model('Transaction', transactionSchema);
  • 前端提交请求时,确保Content-Type为application/json,且请求体包含完整的name、description、amount字段

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 19:05:59